Programs & Examples On #Expando

An expando is an custom property attached to a document object.

Creating JSON on the fly with JObject

There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.

In these cases you can do:

using Newtonsoft.Json.Linq;

JObject jsonObject =
     new JObject(
             new JProperty("Date", DateTime.Now),
             new JProperty("Album", "Me Against The World"),
             new JProperty("Year", "James 2Pac-King's blog."),
             new JProperty("Artist", "2Pac")
         )

More documentation here: http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

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

An easy solution to overcome this problem is to set your default encoding to utf8. Follow is an example

import sys

reload(sys)
sys.setdefaultencoding('utf8')

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.

Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.

edit

Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.

You use the same casting technique to iterate over the fields:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

The above code and more can be found by clicking on that link.

How do I reflect over the members of dynamic object?

Requires Newtonsoft Json.Net

A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:

public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
    JObject attributesAsJObject = dynamicToGetPropertiesFor;
    Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
    List<string> toReturn = new List<string>();
    foreach (string key in values.Keys)
    {
        toReturn.Add(key);                
    }
    return toReturn;
}

Then you simply foreach like this:

foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
    dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
    // And
    dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}

Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.

What are the true benefits of ExpandoObject?

The real benefit for me is the totally effortless data binding from XAML:

public dynamic SomeData { get; set; }

...

SomeData.WhatEver = "Yo Man!";

...

 <TextBlock Text="{Binding SomeData.WhatEver}" />

How to get a div to resize its height to fit container?

You probably are going to want to use the following declaration:

height: 100%;

This will set the div's height to 100% of its containers height, which will make it fill the parent div.

How to initialize an array in Kotlin with values?

Old question, but if you'd like to use a range:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()

Yields nearly the same result as:

var numbers = Array(5, { i -> i*10 + 10 })

result: 10, 20, 30, 40, 50

I think the first option is a little more readable. Both work.

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Why is @font-face throwing a 404 error on woff files?

Actually the @Ian Robinson answer works well but Chrome will continue complain with that message : "Resource interpreted as Font but transferred with MIME type application/x-woff"

If you get that, you can change from

application/x-woff

to

application/x-font-woff

and you will not have any Chrome console errors anymore !

(tested on Chrome 17)

How to pause javascript code execution for 2 seconds

You can use setTimeout to do this

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);

What is the difference between Sessions and Cookies in PHP?

Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.

You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.

If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.

Screenshot of a Cookie

How to print a string multiple times?

If you want to print something = '@' 2 times in a line, you can write this:

print(something * 2)

If you want to print 4 lines of something, you can use a for loop:

for i in range(4):
     print(something)

How to use ScrollView in Android?

How to use ScrollView

Using ScrollView is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout.

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- things to scroll -->

    </LinearLayout>
</ScrollView>

If you want to scroll things horizontally, then use a HorizontalScrollView.

Making the content fill the screen

As is talked about in this post, sometimes you want the ScrollView content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.

If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.

enter image description here

This can be solved with a combination of using fillViewPort on the ScrollView and using a layout weight on the content. Using fillViewPort makes the ScrollView fill the parent area. Setting the layout_weight on one of the views in the LinearLayout makes that view expand to fill any extra space.

enter image description here

Here is the XML

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">                        <--- fillViewport

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textview"
            android:layout_height="0dp"                <--- 
            android:layout_weight="1"                  <--- set layout_weight
            android:layout_width="match_parent"
            android:padding="6dp"
            android:text="hello"/>

        <LinearLayout
            android:layout_height="wrap_content"       <--- wrap_content
            android:layout_width="match_parent"
            android:background="@android:drawable/bottom_bar"
            android:gravity="center_vertical">

            <Button
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Accept" />

            <Button
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Refuse" />

        </LinearLayout>
    </LinearLayout>
</ScrollView>

The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.

python-pandas and databases like mysql

This should work just fine.

import MySQLdb as mdb
import pandas as pd
con = mdb.connect(‘127.0.0.1’, ‘root’, ‘password’, ‘database_name’);
with con:
 cur = con.cursor()
 cur.execute(“select random_number_one, random_number_two, random_number_three from randomness.a_random_table”)
 rows = cur.fetchall()
 df = pd.DataFrame( [[ij for ij in i] for i in rows] )
 df.rename(columns={0: ‘Random Number One’, 1: ‘Random Number Two’, 2: ‘Random Number Three’}, inplace=True);
 print(df.head(20))

How to subtract days from a plain Date?

split your date into parts, then return a new Date with the adjusted values

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;

Changing element style attribute dynamically using JavaScript

In addition to other answers, if you want to use the dash notition for style properties, you can also use:

document.getElementById("xyz").style["padding-top"] = "10px";

How to run Spyder in virtual environment?

Additional to tomaskazemekas's answer: you should install spyder in that virtual environment by:

conda install -n myenv spyder

(on Windows, for Linux or MacOS, you can search for similar commands)

Is there a short contains function for lists?

In addition to what other have said, you may also be interested to know that what in does is to call the list.__contains__ method, that you can define on any class you write and can get extremely handy to use python at his full extent.  

A dumb use may be:

>>> class ContainsEverything:
    def __init__(self):
        return None
    def __contains__(self, *elem, **k):
        return True


>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>         

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

It sounds like a slippery slope to something that'd be posted on thedailywtf.com, "ManagerOfPeopleWhoHaveMortgages", etc.

I suppose it's right that one monolithic Manager class is not good design, but using 'Manager' is not bad. Instead of UserManager we might break it down to UserAccountManager, UserProfileManager, UserSecurityManager, etc.

'Manager' is a good word because it clearly shows a class is not representing a real-world 'thing'. 'AccountsClerk' - how am I supposed to tell if that's a class which manages user data, or represents someone who is an Accounts Clerk for their job?

Append a single character to a string or char array in java?

1. String otherString = "helen" + character;

2. otherString +=  character;

Left Join With Where Clause

If I understand your question correctly you want records from the settings database if they don't have a join accross to the character_settings table or if that joined record has character_id = 1.

You should therefore do

SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT OUTER JOIN `character_settings` 
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1' OR
`character_settings`.character_id is NULL

How can foreign key constraints be temporarily disabled using T-SQL?

To disable the constraint you have ALTER the table using NOCHECK

ALTER TABLE [TABLE_NAME] NOCHECK CONSTRAINT [ALL|CONSTRAINT_NAME]

To enable you to have to use double CHECK:

ALTER TABLE [TABLE_NAME] WITH CHECK CHECK CONSTRAINT [ALL|CONSTRAINT_NAME]
  • Pay attention to the double CHECK CHECK when enabling.
  • ALL means for all constraints in the table.

Once completed, if you need to check the status, use this script to list the constraint status. Will be very helpfull:

    SELECT (CASE 
        WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED'
        ELSE 'DISABLED'
        END) AS STATUS,
        OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME,
        OBJECT_NAME(FKEYID) AS TABLE_NAME,
        COL_NAME(FKEYID, FKEY) AS COLUMN_NAME,
        OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME,
        COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME
   FROM SYSFOREIGNKEYS
ORDER BY TABLE_NAME, CONSTRAINT_NAME,REFERENCED_TABLE_NAME, KEYNO 

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

Lock screen orientation (Android)

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

Foreach loop in java for a custom object list

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}

Mongoimport of json file

I was able to fix the error using the following query:

mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray

Hopefully this is helpful to someone.

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

Reinstalling java didn't help me. But the trick to put the JAVA_HOME variable at the beginning of the env-vars. The problem occoured after an upgrade from jdk1.7.0_11 to jdk1.7.0_13

Programmatically obtain the phone number of the Android phone

There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).

I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

Converting Select results into Insert script - SQL Server

I think its also possible with adhoc queries you can export result to excel file and then import that file into your datatable object or use it as it is and then import the excel file into the second database have a look at this link this can help u alot.

http://vscontrols.blogspot.com/2010/09/import-and-export-excel-to-sql-server.html

Does hosts file exist on the iPhone? How to change it?

Don't change the DNS on the phone. Instead, connect with wifi to the local network and you are all set.

At my office, we have internal servers with internal DNS that are not exposed to the Internet. I just connect with iPhone to the office wifi and can then access them fine.

YMMV, but instead of configuring the phone DNS, it feels to me that just setting up local internal DNS and wifi is a cleaner and easier solution.

Can Powershell Run Commands in Parallel?

This has been answered thoroughly. Just want to post this method i have created based on Powershell-Jobs as a reference.

Jobs are passed on as a list of script-blocks. They can be parameterized. Output of the jobs is color-coded and prefixed with a job-index (just like in a vs-build-process, as this will be used in a build) Can be used to startup multiple servers at a time or running build steps in parallel or so..

function Start-Parallel {
    param(
        [ScriptBlock[]]
        [Parameter(Position = 0)]
        $ScriptBlock,

        [Object[]]
        [Alias("arguments")]
        $parameters
    )

    $jobs = $ScriptBlock | ForEach-Object { Start-Job -ScriptBlock $_ -ArgumentList $parameters }
    $colors = "Blue", "Red", "Cyan", "Green", "Magenta"
    $colorCount = $colors.Length

    try {
        while (($jobs | Where-Object { $_.State -ieq "running" } | Measure-Object).Count -gt 0) {
            $jobs | ForEach-Object { $i = 1 } {
                $fgColor = $colors[($i - 1) % $colorCount]
                $out = $_ | Receive-Job
                $out = $out -split [System.Environment]::NewLine
                $out | ForEach-Object {
                    Write-Host "$i> "-NoNewline -ForegroundColor $fgColor
                    Write-Host $_
                }
                
                $i++
            }
        }
    } finally {
        Write-Host "Stopping Parallel Jobs ..." -NoNewline
        $jobs | Stop-Job
        $jobs | Remove-Job -Force
        Write-Host " done."
    }
}

sample output:

sample output

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

Sending Windows key using SendKeys

Alt+F4 is working only in brackets

SendKeys.SendWait("(%{F4})");

What is the difference between range and xrange functions in Python 2.X?

The difference decreases for smaller arguments to range(..) / xrange(..):

$ python -m timeit "for i in xrange(10111):" " for k in range(100):" "  pass"
10 loops, best of 3: 59.4 msec per loop

$ python -m timeit "for i in xrange(10111):" " for k in xrange(100):" "  pass"
10 loops, best of 3: 46.9 msec per loop

In this case xrange(100) is only about 20% more efficient.

CRC32 C or C++ implementation

rurban's fork of SMHasher (the original SMHasher seems abandoned) has hardware CRC32 support. The changes were added before the initial commit, but try comparing the new CMakeLists.txt and the old one (which doesn't mention SSE at all).

The best option is probably Intel's zlib fork with PCLMULQDQ support described in this paper. This library also has the SSE 4.2 optimizations.

If you don't need portability and you're on Linux, you can use the kernel's implementation (which is hardware accelerated if available): https://stackoverflow.com/a/11156040/309483

How to bind an enum to a combobox control in WPF?

Universal apps seem to work a bit differently; it doesn't have all the power of full-featured XAML. What worked for me is:

  1. I created a list of the enum values as the enums (not converted to strings or to integers) and bound the ComboBox ItemsSource to that
  2. Then I could bind the ComboBox ItemSelected to my public property whose type is the enum in question

Just for fun I whipped up a little templated class to help with this and published it to the MSDN Samples pages. The extra bits let me optionally override the names of the enums and to let me hide some of the enums. My code looks an awful like like Nick's (above), which I wish I had seen earlier.

Running the sample; it includes multiple twoway bindings to the enum

git push says "everything up-to-date" even though I have local changes

My issue was that my local branch had a different name than the remote branch. I was able to push by doing the following:

$ git push origin local-branch-name:remote-branch-name

(Credit to https://penandpants.com/2013/02/07/git-pushing-to-a-remote-branch-with-a-different-name/)

Should C# or C++ be chosen for learning Games Programming (consoles)?

Hey, if BASIC is good enough for Gorillas, it's good enough for me.

Bootstrap change carousel height

The following should work

.carousel .item {
  height: 300px;
}

.item img {
    position: absolute;
    top: 0;
    left: 0;
    min-height: 300px;
}

JSFille for reference.

Convert date to YYYYMM format

I know it is an old topic, but If your SQL server version is higher than 2012.

There is another simple option can choose, FORMAT function.

SELECT FORMAT(GetDate(),'yyyyMM')

sqlfiddle

Javascript Object push() function

Do :


var data = new Array();
var tempData = new Array();

Generate a range of dates using SQL

I had the same requirement - I just use this. User enters the number of days by which he/she wants to limit the calendar range to.

  SELECT DAY, offset
    FROM (SELECT to_char(SYSDATE, 'DD-MON-YYYY') AS DAY, 0 AS offset
            FROM DUAL
          UNION ALL
          SELECT to_char(SYSDATE - rownum, 'DD-MON-YYYY'), rownum
            FROM all_objects d)
            where offset <= &No_of_days

I use the above result set as driving view in LEFT OUTER JOIN with other views involving tables which have dates.

Text overflow ellipsis on two lines

My solution reuses the one of amcdnl, but my fallback consist of using a height for the text container:

.my-caption h4 {
    display: -webkit-box;
    margin: 0 auto;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;

    height: 40px;/* Fallback for non-webkit */
}

href overrides ng-click in Angular.js

//for dynamic elements - if you want it in ng-repeat do below code

angular.forEach($scope.data, function(value, key) {
     //add new value to object
    value.new_url  = "your url";
});

 <div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

An absolute xpath in HTML DOM starts with /html e.g.

/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.

.//*[@id='answers']/h2[1]/a[1]

You can use firepath (firebug) for generating both types of xpaths

It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)

Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element

What is PostgreSQL equivalent of SYSDATE from Oracle?

The following functions are available to obtain the current date and/or time in PostgreSQL:

CURRENT_TIME

CURRENT_DATE

CURRENT_TIMESTAMP

Example

SELECT CURRENT_TIME;
08:05:18.864750+05:30

SELECT CURRENT_DATE;
2020-05-14

SELECT CURRENT_TIMESTAMP;
2020-05-14 08:04:51.290498+05:30

postgresql docs

Getting a machine's external IP address with Python

The most simple (non python) working solution I can think of is

wget -q -O- icanhazip.com

I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.

from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])

You can of course add some error checking, a timeout condition and some convenience:

#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json

try:
    url = 'http://api.hostip.info/get_json.php'
    info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
    print(info['ip'])
except URLError as e:
    print(e.reason, end=' ') # e.g. 'timed out'
    print('(are you connected to the internet?)')
except KeyboardInterrupt:
    pass

How to use NSJSONSerialization

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

In above JSON data, you are showing that we have an array contaning the number of dictionaries.

You need to use this code for parsing it:

NSError *e = nil;
NSArray *JSONarray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
        for(int i=0;i<[JSONarray count];i++)
        {
            NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"id"]);
             NSLog(@"%@",[[JSONarray objectAtIndex:i]objectForKey:@"name"]);
        }

For swift 3/3+

   //Pass The response data & get the Array
    let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [AnyObject]
    print(jsonData)
    // considering we are going to get array of dictionary from url

    for  item  in jsonData {
        let dictInfo = item as! [String:AnyObject]
        print(dictInfo["id"])
        print(dictInfo["name"])
    }

RadioGroup: How to check programmatically

In your layout you can add android:checked="true" to CheckBox you want to be selected.

Or programmatically, you can use the setChecked method defined in the checkable interface:

RadioButton b = (RadioButton) findViewById(R.id.option1); b.setChecked(true);

Less aggressive compilation with CSS3 calc

There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974

@variable: 2em;

body{ width: calc(~"100% - @{variable} * 2");}

By using the curly brackets you don't need to close and reopen the escaping quotes.

How to determine day of week by passing specific date?

You can use below method to get Day of the Week by passing a specific date,

Here for the set method of Calendar class, Tricky part is the index for the month parameter will starts from 0.

public static String getDay(int day, int month, int year) {

        Calendar cal = Calendar.getInstance();

        if(month==1){
            cal.set(year,0,day);
        }else{
            cal.set(year,month-1,day);
        }

        int dow = cal.get(Calendar.DAY_OF_WEEK);

        switch (dow) {
        case 1:
            return "SUNDAY";
        case 2:
            return "MONDAY";
        case 3:
            return "TUESDAY";
        case 4:
            return "WEDNESDAY";
        case 5:
            return "THURSDAY";
        case 6:
            return "FRIDAY";
        case 7:
            return "SATURDAY";
        default:
            System.out.println("GO To Hell....");
        }

        return null;
    }

Where does gcc look for C and C++ header files?

`gcc -print-prog-name=cc1plus` -v

This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.

You will get a reliable answer for your specific setup.

Likewise, for the C preprocessor:

`gcc -print-prog-name=cpp` -v

What's the difference between a Python module and a Python package?

A late answer, yet another definition:

A package is represented by an imported top-entity which could either be a self-contained module, or the __init__.py special module as the top-entity from a set of modules within a sub directory structure.

So physically a package is a distribution unit, which provides one or more modules.

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Upgrading PHP in XAMPP for Windows?

  1. Go to phpinfo(), press ctrl+f, and type thread to check the value.
  2. If it is enabled download the non thread safe version, otherwise download the thread safe version from here (zip).
  3. Extract it, and rename the folder to php.
  4. Go to your xampp folder rename the default php folder to something else.
  5. Copy the extracted (renamed php) folder in xampp directory.
  6. Copy the php.ini file from default/old php folder (That you renamed) and paste it into the new php folder.
  7. Restart xampp server and you're good to go.

Installing packages in Sublime Text 2

This recently worked for me. You just need to add to your packages, so that the package manager would be aware of the packages:

  1. Add the Sublime Text 2 Repository to your Synaptic Package Manager:

    sudo add-apt-repository ppa:webupd8team/sublime-text-2
    
  2. Update

    sudo apt-get update
    
  3. Install Sublime Text:

    sudo apt-get install sublime-text
    

White space showing up on right side of page when background image should extend full length of page

This is a pretty old question, but I thought I'd add my 2 cents. I've tried the above solutions, including the ghost css, which I will definitely be saving for future use. But none of these worked in my situation. Here's how I fixed my issue. Hopefully this will help someone else.

Open inspector (or whatever your preference) and starting with the first div in body tag, add display: none; to just that element. If the scroll bar disappears, you know that element contains the element that's causing the issue. Then, remove the first css rule and go down one level into the containing element. Add the css to that div, and if the scroll bar goes away, you know that element is either causing, or containing the offending element. If adding the CSS does nothing, you know it was not that div that caused the issue, and either another div in the container is causing it, or the container itself is causing it.

This may be too time consuming for some. Lucky for me, my issue was in the header, but I can imagine this taking a bit of time if your issue was say, in the footer or something.

How do I reference the input of an HTML <textarea> control in codebehind?

Missed property runat="server" or in code use Request.Params["TextArea1"]

How do I iterate over a JSON structure?

Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

RESULT: John Doe 25

Get size of a View in React Native

You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

Hope to help you!

Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

Round button with text and icon in flutter

You can achieve that by using a FlatButton that contains a Column (for showing a text below the icon) or a Row (for text next to the icon), and then having an Icon Widget and a Text widget as children.

Here's an example:

class MyPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) =>
      Scaffold(
        appBar: AppBar(
          title: Text("Hello world"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                onPressed: () => {},
                color: Colors.orange,
                padding: EdgeInsets.all(10.0),
                child: Column( // Replace with a Row for horizontal icon + text
                  children: <Widget>[
                    Icon(Icons.add),
                    Text("Add")
                  ],
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => {},
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      );
}

This will produce the following:

Result

Start service in Android

I like to make it more dynamic

Class<?> serviceMonitor = MyService.class; 


private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService()  { context.stopService(new Intent(context, serviceMonitor));  }

do not forget the Manifest

<service android:enabled="true" android:name=".MyService.class" />

ASP.NET MVC Razor pass model to layout

public interface IContainsMyModel
{
    ViewModel Model { get; }
}

public class ViewModel : IContainsMyModel
{
    public string MyProperty { set; get; }
    public ViewModel Model { get { return this; } }
}

public class Composition : IContainsMyModel
{
    public ViewModel ViewModel { get; set; }
}

Use IContainsMyModel in your layout.

Solved. Interfaces rule.

How to hide element label by element id in CSS?

Without a class or an id, and with your specific html:

table tr td label {display:none}

Otherwise if you have jQuery

$('label[for="foo"]').css('display', 'none');

Uncaught TypeError: Cannot read property 'top' of undefined

The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, let's say you have the following:

<a href="#examples">Skip to examples</a>

There has to be an element in the page with that id, example:

<div id="examples">Here are the examples</div>

So make sure that each one of the links are matched inside the page with it's corresponding anchor.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I am using spring 3.0 and Hibernate 3.6 in my project. I ran into the same error just now. Googling this error message brought me to this page.

Funtik's comment on Jan 17 '12 at 8:49 helped me resolve the issue-

"This tells me that javassist cannot be accessed. How do you include this library into the project?"

So, I included java assist in my maven pom file as below:

<dependency>
    <groupId>javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.12.1.GA</version>
</dependency>

This resolved the issue for me. Thanks Funtik.

adding 30 minutes to datetime php/mysql

If you are using MySQL you can do it like this:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;


For a pure PHP solution use strtotime

strtotime('+ 30 minute',$yourdate);

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

Object cannot be cast from DBNull to other types

Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN

Actual Code which I faced error:

Before changed the code:

    if( ds.Tables[0].Rows[0][0] == null ) //   Which is not working

     {
            seqno  = 1; 
      }
    else
    {
          seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
     }

After changed the code:

   if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
        {
                    seqno  = 1; 
         }
            else
            {
                  seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
             }

Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.

Find multiple files and rename them in Linux

You can use find to find all matching files recursively:

$ find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \;

EDIT: what the '{}' and \; are?

The -exec argument makes find execute rename for every matching file found. '{}' will be replaced with the path name of the file. The last token, \; is there only to mark the end of the exec expression.

All that is described nicely in the man page for find:

 -exec utility [argument ...] ;
         True if the program named utility returns a zero value as its
         exit status.  Optional arguments may be passed to the utility.
         The expression must be terminated by a semicolon (``;'').  If you
         invoke find from a shell you may need to quote the semicolon if
         the shell would otherwise treat it as a control operator.  If the
         string ``{}'' appears anywhere in the utility name or the argu-
         ments it is replaced by the pathname of the current file.
         Utility will be executed from the directory from which find was
         executed.  Utility and arguments are not subject to the further
         expansion of shell patterns and constructs.

How to get the element clicked (for the whole document)?

use the following inside the body tag

<body onclick="theFunction(event)">

then use in javascript the following function to get the ID

<script>
function theFunction(e)
{ alert(e.target.id);}

Cordova : Requirements check failed for JDK 1.8 or greater

  1. Go to Control panel Home
  2. Advanced System Settings
  3. Environment Variables
  4. Choose JAVA_HOME
  5. edit
  6. variable value for the 1.8 one

Getting realtime output using subprocess

if you just want to forward the log to console in realtime

Below code will work for both

 p = subprocess.Popen(cmd,
                         shell=True,
                         cwd=work_dir,
                         bufsize=1,
                         stdin=subprocess.PIPE,
                         stderr=sys.stderr,
                         stdout=sys.stdout)

Options for initializing a string array

string[] str = new string[]{"1","2"};
string[] str = new string[4];

Gradle to execute Java class (without modifying build.gradle)

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

task runApp(type:JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}

where you set your default main class.

python modify item in list, save back in list

A common idiom to change every element of a list looks like this:

for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result

This can be rewritten using enumerate() as:

for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result

See enumerate.

php - How do I fix this illegal offset type error

There are probably less than 20 entries in your xml.

change the code to this

for ($i=0;$i< sizeof($xml->entry); $i++)
...

Jquery asp.net Button Click Event via ajax

This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:

When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.

$(document).ready(function() {
  $("input[id$='btnAwesome']").click(function() {
    // Do client side button click stuff here.
  });
});

The id$= is doing a regex match for an id ENDING with btnAwesome.

Edit:

Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.

The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.

Make a dictionary with duplicate keys in Python

You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html

In a dict, if a key is an object, there are no duplicate problems.

For example:

class p(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name
    def __str__(self):
        return self.name
d = {p('k'): 1, p('k'): 2}

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

HTML:

<div  ng-repeat="scannedDevice in ScanResult">
        <!--GridStarts-->
          <div >
              <img ng-src={{'./assets/img/PlaceHolder/Test.png'}} 
                   <!--Pass Param-->
                   ng-click="connectDevice(scannedDevice.id)"
                   altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}" 
                   onerror="this.src = $(this).attr('altSrc')">
           </div>    
 </div>

Java Script:

   //Global Variables
    var  ANGULAR_APP = angular.module('TestApp',[]);

    ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {

      //Variables
      $scope.ScanResult = [];

      //Pass Parameter
      $scope.connectDevice = function(deviceID) {
            alert("Connecting : "+deviceID );
        };
     }]);

How to search a Git repository by commit message?

To search the commit log (across all branches) for the given text:

git log --all --grep='Build 0051'

To search the actual content of commits through a repo's history, use:

git grep 'Build 0051' $(git rev-list --all)

to show all instances of the given text, the containing file name, and the commit sha1.

Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the -g flag (short for --walk-reflogs:

git log -g --grep='Build 0051'

EDIT: if you seem to have lost your history, check the reflog as your safety net. Look for Build 0051 in one of the commits listed by

git reflog

You may have simply set your HEAD to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.

To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)

git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
# git checkout HEAD@{10}
git checkout -b build_0051 # make a new branch with the build_0051 as the tip

Checking if an input field is required using jQuery

$('form#register input[required]')

It will only return inputs which have required attribute.

Converting integer to string in Python

Here is a simpler solution:

one = "1"
print(int(one))

Output console

>>> 1

In the above program, int() is used to convert the string representation of an integer.

Note: A variable in the format of string can be converted into an integer only if the variable is completely composed of numbers.

In the same way, str() is used to convert an integer to string.

number = 123567
a = []
a.append(str(number))
print(a) 

I used a list to print the output to highlight that variable (a) is a string.

Output console

>>> ["123567"]

But to understand the difference how a list stores a string and integer, view the below code first and then the output.

Code

a = "This is a string and next is an integer"
listone=[a, 23]
print(listone)

Output console

>>> ["This is a string and next is an integer", 23]

What does request.getParameter return?

Per the Javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

jQuery find parent form

To me, this looks like the simplest/fastest:

$('form input[type=submit]').click(function() { // attach the listener to your button
   var yourWantedObjectIsHere = $(this.form);   // use the native JS object with `this`
});

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

I would change the implementation slightly:

First, I create a UnknownMatchException:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UnknownMatchException extends RuntimeException {
    public UnknownMatchException(String matchId) {
        super("Unknown match: " + matchId);
    }
}

Note the use of @ResponseStatus, which will be recognized by Spring's ResponseStatusExceptionResolver. If the exception is thrown, it will create a response with the corresponding response status. (I also took the liberty of changing the status code to 404 - Not Found which I find more appropriate for this use case, but you can stick to HttpStatus.BAD_REQUEST if you like.)


Next, I would change the MatchService to have the following signature:

interface MatchService {
    public Match findMatch(String matchId);
}

Finally, I would update the controller and delegate to Spring's MappingJackson2HttpMessageConverter to handle the JSON serialization automatically (it is added by default if you add Jackson to the classpath and add either @EnableWebMvc or <mvc:annotation-driven /> to your config, see the reference docs):

@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Match match(@PathVariable String matchId) {
    // throws an UnknownMatchException if the matchId is not known 
    return matchService.findMatch(matchId);
}

Note, it is very common to separate the domain objects from the view objects or DTO objects. This can easily be achieved by adding a small DTO factory that returns the serializable JSON object:

@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MatchDTO match(@PathVariable String matchId) {
    Match match = matchService.findMatch(matchId);
    return MatchDtoFactory.createDTO(match);
}

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

How to prevent XSS with HTML/PHP?

You are also able to set some XSS related HTTP response headers via header(...)

X-XSS-Protection "1; mode=block"

to be sure, the browser XSS protection mode is enabled.

Content-Security-Policy "default-src 'self'; ..."

to enable browser-side content security. See this one for Content Security Policy (CSP) details: http://content-security-policy.com/ Especially setting up CSP to block inline-scripts and external script sources is helpful against XSS.

for a general bunch of useful HTTP response headers concerning the security of you webapp, look at OWASP: https://www.owasp.org/index.php/List_of_useful_HTTP_headers

Converting HTML to plain text in PHP for e-mail

You can test this function

function html2text($Document) {
    $Rules = array ('@<script[^>]*?>.*?</script>@si',
                    '@<[\/\!]*?[^<>]*?>@si',
                    '@([\r\n])[\s]+@',
                    '@&(quot|#34);@i',
                    '@&(amp|#38);@i',
                    '@&(lt|#60);@i',
                    '@&(gt|#62);@i',
                    '@&(nbsp|#160);@i',
                    '@&(iexcl|#161);@i',
                    '@&(cent|#162);@i',
                    '@&(pound|#163);@i',
                    '@&(copy|#169);@i',
                    '@&(reg|#174);@i',
                    '@&#(d+);@e'
             );
    $Replace = array ('',
                      '',
                      '',
                      '',
                      '&',
                      '<',
                      '>',
                      ' ',
                      chr(161),
                      chr(162),
                      chr(163),
                      chr(169),
                      chr(174),
                      'chr()'
                );
  return preg_replace($Rules, $Replace, $Document);
}

Mongoose: findOneAndUpdate doesn't return updated document

In some scenarios {new: true} is not working. Then you can try this.

{'returnNewDocument':true}

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Why not check if for nothing?

if not inputbox("bleh") = nothing then
'Code
else
' Error
end if

This is what i typically use, because its a little easier to read.

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

How to "git clone" including submodules?

Submodules parallel fetch aims at reducing the time required to fetch a repositories and all of its related submodules by enabling the fetching of multiple repositories at once. This can be accomplished by using the new --jobs option, e.g.:

git fetch --recurse-submodules --jobs=4

According to Git team, this can substantially speed up updating repositories that contain many submodules. When using --recurse-submodules without the new --jobs option, Git will fetch submodules one by one.

Source: http://www.infoq.com/news/2016/03/git28-released

How to keep one variable constant with other one changing with row in excel

You put it as =(B0+4)/($A$0)

You can also go across WorkSheets with Sheet1!$a$0

How to reenable event.preventDefault?

$('form').submit( function(e){

     e.preventDefault();

     //later you decide you want to submit
     $(this).trigger('submit');     or     $(this).trigger('anyEvent');

Twitter Bootstrap - full width navbar

You have to add col-md-12 to your inner-navbar. md is for desktop .you can choose other options from bootstrap's list of options . 12 in col-md-12 is for full width .If you want half-width you can use 6 instead of 12 .for e.g. col-md-6.

Here is the solution to your question

    <div class="container">
       <div class="navbar">
          <div class="navbar-inner col-md-12">
               <!-- nav bar items here -->
          </div>
       </div>
   </div>

Reset auto increment counter in postgres

If you created the table product with an id column, then the sequence is not simply called product, but rather product_id_seq (that is, ${table}_${column}_seq).

This is the ALTER SEQUENCE command you need:

ALTER SEQUENCE product_id_seq RESTART WITH 1453

You can see the sequences in your database using the \ds command in psql. If you do \d product and look at the default constraint for your column, the nextval(...) call will specify the sequence name too.

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

Objective-C: Calling selectors with multiple arguments

Think the class should be defined as:

- (void) myTestWithSomeString:(NSString *) astring{
    NSLog(@"hi, %s", astring);
}

You only have a single parameter so you should only have a single :

You might want to consider using %@ in your NSLog also - it is just a good habit to get into - will then write out any object - not just strings.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

jQuery callback on image load (even when the image is cached)

Do you really have to do it with jQuery? You can attach the onload event directly to your image as well;

<img src="/path/to/image.jpg" onload="doStuff(this);" />

It will fire every time the image has loaded, from cache or not.

Comparing two java.util.Dates to see if they are in the same day

How about:

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

You can also set the timezone to the SimpleDateFormat, if needed.

m2e lifecycle-mapping not found

Here's how I do it: I put m2e's lifecycle-mapping plugin in a separate profile instead of the default <build> section. the profile is auto-activated during eclipse builds by presence of a m2e property (instead of manual activation in settings.xml or otherwise). this will handle the m2e cases, while command-line maven will simply skip the profile and the m2e lifecycle-mapping plugin without any warnings, and everybody is happy.

<project>
  ...
  <profiles>
    ...
    <profile>
      <id>m2e</id>
      <!-- This profile is only active when the property "m2e.version"
        is set, which is the case when building in Eclipse with m2e. -->
      <activation>
        <property>
          <name>m2e.version</name>
        </property>
      </activation>
      <build>
        <pluginManagement>
          <plugins>
            <plugin>
              <groupId>org.eclipse.m2e</groupId>
              <artifactId>lifecycle-mapping</artifactId>
              <version>1.0.0</version>
              <configuration>
                <lifecycleMappingMetadata>
                  <pluginExecutions>
                    <pluginExecution>
                      <pluginExecutionFilter>
                        <groupId>...</groupId>
                        <artifactId>...</artifactId>
                        <versionRange>[0,)</versionRange>
                        <goals>
                          <goal>...</goal>
                        </goals>
                      </pluginExecutionFilter>
                      <action>

                        <!-- either <ignore> XOR <execute>,
                          you must remove the other one. -->

                        <!-- execute: tells m2e to run the execution just like command-line maven.
                          from m2e's point of view, this is not recommended, because it is not
                          deterministic and may make your eclipse unresponsive or behave strangely. -->
                        <execute>
                          <!-- runOnIncremental: tells m2e to run the plugin-execution
                            on each auto-build (true) or only on full-build (false). -->
                          <runOnIncremental>false</runOnIncremental>
                        </execute>

                        <!-- ignore: tells m2eclipse to skip the execution. -->
                        <ignore />

                      </action>
                    </pluginExecution>
                  </pluginExecutions>
                </lifecycleMappingMetadata>
              </configuration>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </profile>
    ...
  </profiles>
  ...
</project>

What's the quickest way to multiply multiple cells by another number?

As one of the answers above says: " then drag the formula fill handle." This KEY feature is not mentioned in MS's explanation, nor in others here. I spent over an hour trying to follow the various instructions, to no avail. This is because you have to click and hold near the bottom of the cell just right (and at least on my computer that is not at all easy) so that a sort of "handle" appears. Once you're luck enough to get that, then carefully slide ["drag"] your cursor down to the lowermost of the cells you want to be multiplied by the constant. The products should show up in each cell as you move down. Just dragging down will give you only the answer in the first cell and a lot of white space.

Change the color of a bullet in a html list?

Hello maybe this answer is late but is the correct one to achieve this.

Ok the fact is that you must specify an internal tag to make the LIst text be on the usual black (or what ever you want to get it). But is also true that you can REDEFINE any TAGS and internal tags with CSS. So the best way to do this use a SHORTER tag for the redefinition

Usign this CSS definition:

li { color: red; }
li b { color: black; font_weight: normal; }
.c1 { color: red; }
.c2 { color: blue; }
.c3 { color: green; }

And this html code:

<ul>
<li><b>Text 1</b></li>
<li><b>Text 2</b></li>
<li><b>Text 3</b></li>
</ul>

You get required result. Also you can make each disc diferent color:

<ul>
    <li class="c1"><b>Text 1</b></li>
    <li class="c2"><b>Text 2</b></li>
    <li class="c3"><b>Text 3</b></li>
 </ul>

How to set Internet options for Android emulator?

Hi me also faced same issue , solved using below steps:

cause 1:

Add internet permission in your android application

cause 2:

Check the manually your default application is able access internet or not if not its problem of your emulator , check in your internet connection in your pc

try below method to connect net in your pc

try explicitly specifying DNS server settings, this worked for me.

In Eclipse:

Window>Preferences>Android>Launch

Default emulator options: -dns-server 8.8.8.8,8.8.4.4**

cause 3:

check : check if you are using more than one internet connection to your pc like one is LAN second one is Modem , so disable all lan or modem .

How to get the <html> tag HTML with JavaScript / jQuery?

In addition to some of the other answers, you could also access the HTML element via:

var htmlEl = document.body.parentNode;

Then you could get the inner HTML content:

var inner = htmlEl.innerHTML;

Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode seems to be quite a bit faster.

After you have the HTML element, you can mess with the attributes with the getAttribute and setAttribute methods.

For the DOCTYPE, you could use document.doctype, which was elaborated upon in this question.

String array initialization in Java

You can do the following during declaration:

String names[] = {"Ankit","Bohra","Xyz"};

And if you want to do this somewhere after declaration:

String names[];
names = new String[] {"Ankit","Bohra","Xyz"};

C++ STL Vectors: Get iterator from index?

Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:

int main()
{

void foo(const char *);

sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');

foo(&vec[0]);
}

Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...

Therefore in your exemple it leads to

vector.insert(pos, &vec[first_index], &vec[last_index]);

How do I edit $PATH (.bash_profile) on OSX?

If you are using MAC Catalina you need to update the .zshrc file instead of .bash_profile or .profile

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

How to put a tooltip on a user-defined function

I know you've accepted an answer for this, but there's now a solution that lets you get an intellisense style completion box pop up like for the other excel functions, via an Excel-DNA add in, or by registering an intellisense server inside your own add in. See here.

Now, i prefer the C# way of doing it - it's much simpler, as inside Excel-DNA, any class that implements IExcelAddin is picked up by the addin framework and has AutoOpen() and AutoClose() run when you open/close the add in. So you just need this:

namespace MyNameSpace {
    public class Intellisense : IExcelAddIn {
        public void AutoClose() {
        }
        public void AutoOpen() {
            IntelliSenseServer.Register();
        }
    }
}

and then (and this is just taken from the github page), you just need to use the ExcelDNA annotations on your functions:

[ExcelFunction(Description = "A useful test function that adds two numbers, and returns the sum.")]
public static double AddThem(
    [ExcelArgument(Name = "Augend", Description = "is the first number, to which will be added")] 
    double v1,
    [ExcelArgument(Name = "Addend", Description = "is the second number that will be added")]     
    double v2)
{
    return v1 + v2;
}

which are annotated using the ExcelDNA annotations, the intellisense server will pick up the argument names and descriptions.

enter image description here enter image description here

There are examples for using it with just VBA too, but i'm not too into my VBA, so i don't use those parts.

How can I make space between two buttons in same div?

You can use spacing for Bootstrap and no need for any additional CSS. Just add the classes to your buttons. This is for version 4.

Send POST data on redirect with JavaScript/jQuery?

The answers here can be confusing so i will give you a sample code that i am working with.

To start with note that there is no POST parameter to java script windows.location function that you are referring to.

So you have to...

  1. Dynamically make a form with a POST parameter.

  2. Dynamically put a textbox or textboxes with your desired values to post

  3. Invoke the submit form you dynamically created.

And for the example.

     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));


    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.

On test2.php you can get your values thus.

$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.

MAMP mysql server won't start. No mysql processes are running

What worked for me was removing all files (but not directories) in the mysql dir.

Edit #2 As per answers below, you only need to delete the log files: [ib_logfile0, ib_logfile1]

So quit MAMP and then in the terminal:

rm /Applications/MAMP/db/mysql/ib_logfile* #(or wherever your MAMP is installed)

Edit!: A few people have mentioned that you may want to back up these files first in case anything goes wrong, so maybe just use mv instead:

mv /Applications/MAMP/db/mysql/*  /tmp/.

If this doesn't work go back and kill all processes: sudo killall -9 mysqld

This is also duplicated here: mysql server won't start MAMP

A quick and easy way to join array elements with a separator (the opposite of split) in Java

This options is fast and clear:

  public static String join(String separator, String... values) {
    StringBuilder sb = new StringBuilder(128);
    int end = 0;
    for (String s : values) {
      if (s != null) {
        sb.append(s);
        end = sb.length();
        sb.append(separator);
      }
    }
    return sb.substring(0, end);
  }

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

What are the date formats available in SimpleDateFormat class?

Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
       Date now = new Date();

       //This is just Date's toString method and doesn't involve SimpleDateFormat
       System.out.println("toString(): " + now);  // dow mon dd hh:mm:ss zzz yyyy
       //Shows  "Mon Oct 08 08:17:06 EDT 2012"

       SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
       System.out.println("Format 1:   " + dateFormatter.format(now));
       // Shows  "Mon, 2012-10-8 at 8:17:6 AM EDT"

       dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       System.out.println("Format 2:   " + dateFormatter.format(now));
       // Shows  "Mon 2012.10.08 at 08:17:06 AM EDT"

       dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
       System.out.println("Format 3:   " + dateFormatter.format(now));
       // Shows  "Monday, October 8, 2012"

       // SimpleDateFormat can be used to control the date/time display format:
       //   E (day of week): 3E or fewer (in text xxx), >3E (in full text)
       //   M (month): M (in number), MM (in number with leading zero)
       //              3M: (in text xxx), >3M: (in full text full)
       //   h (hour): h, hh (with leading zero)
       //   m (minute)
       //   s (second)
       //   a (AM/PM)
       //   H (hour in 0 to 23)
       //   z (time zone)
       //  (there may be more listed under the API - I didn't check)

   }

}

Good luck!

How Do I Uninstall Yarn

Try this, it works well on macOS:

$ brew uninstall --force yarn
$ npm uninstall -g yarn
$ yarn -v

v0.24.5 (or your current version)

$ which yarn

/usr/local/bin/yarn

$ rm -rf /usr/local/bin/yarn
$ rm -rf /usr/local/bin/yarnpkg
$ which yarn

yarn not found

$ brew install yarn 
$ brew link yarn
$ yarn -v

v1.17.3 (latest version)

How do I convert from a string to an integer in Visual Basic?

Use Val(txtPrice.text)

I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.

How to completely uninstall Android Studio from windows(v10)?

I was having problem installing the latest v4.1.2 as it was having issue after I start it it shows my old blank project, so things I did were,

Caution: Please move your sdk and projects to a separate location before following steps if you haven't. So it might save your time downloading sdks and stuff.

1- Uninstall old Android Studio Completely (from Contorl panel -> Programs).

2- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Local\Google

3- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Roaming\Google

4- Delete these folders(.android ,.AndroidStudio*, .gradle) located at C:\Users<user_name>\

After doing all this I was managed to have fresh updated Android Studio v4.1.2

How to select a CRAN mirror in R

Add into ~/.Rprofile

local({r <- getOption("repos")
    r["CRAN"] <- "mirror_site"  #for example, https://mirrors.ustc.edu.cn/CRAN/
    options(repos=r)
    options(BioC_mirror="bioc_mirror_site") #if using biocLite
})

When to use "ON UPDATE CASCADE"

  1. Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10 all children parent_id's of 10 will also be updated to 20

  2. If you don't update the field the foreign key refers to, this setting is not needed

  3. Can't think of any other use.

  4. You can't do that as the foreign key constraint would fail.

How to install a python library manually

You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.

The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:

$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install. (Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )

If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:

$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz 
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

Update Git submodule to latest commit on origin

@Jason is correct in a way but not entirely.

update

Update the registered submodules, i.e. clone missing submodules and checkout the commit specified in the index of the containing repository. This will make the submodules HEAD be detached unless --rebase or --merge is specified or the key submodule.$name.update is set to rebase or merge.

So, git submodule update does checkout, but it is to the commit in the index of the containing repository. It does not yet know of the new commit upstream at all. So go to your submodule, get the commit you want and commit the updated submodule state in the main repository and then do the git submodule update.

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

Clear git local cache

git rm --cached *.FileExtension

This must ignore all files from this extension

How to check if input date is equal to today's date?

There is a simpler solution

if (inputDate.getDate() === todayDate.getDate()) {
   // do stuff
}

like that you don't loose the time attached to inputDate if any

Undefined function mysql_connect()

I see that you tagged this with Ubuntu. Most likely the MySQL driver (and possibly MySQL) is not installed. Assuming you have SSH or terminal access and sudo permissions, log into the server and run this:

sudo apt-get install mysql-server mysql-client php5-mysql

If the MySQL packages or the php5-mysql package are already installed, this will update them.


UPDATE

Since this answer still gets the occasional click I am going to update it to include PHP 7. PHP 7 requires a different package for MySQL so you will want to use a different argument for the apt-get command.

# Replace 7.4 with your version of PHP
sudo apt-get install mysql-server mysql-common php7.4 php7.4-mysql

And importantly, mysql_connect() has been deprecated since PHP v5.5.0. Refer the official documentation here: PHP: mysql_connect()

How can I force a hard reload in Chrome for Android

How to reset all data for a given URL / Website on Chrome Mobile for android:

1 - Open the Chrome menu, and tap on the "i (info)" icon

one

2 - tap "Site settings"

two

3 - Tap the trashcan icon

three

That's it, even the most deeply ensconsed service worker for that URL will now die.

How to do Select All(*) in linq to sql

Dim q = From c In TableA
Select c.TableA

ObjectDumper.Write(q)

How can I make Bootstrap columns all the same height?

So yes, Bootstrap 4 does make all the cols in a row equal height, however if you are creating a border around the content inside the row you may find that it appears like the cols are not equal heights!

When I applied height: 100% to the element inside the col I found that I lost my margin.

My solution is to use padding on the col's div (instead of a margin on the inner element). Like so:

<div class="container">
    <div class="row">
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
    </div>
</div>

The above code example uses Bootstrap 4.1 to create a set of nine boxes with a border

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A typical algo for tic-tac-toe should look like this:

Board : A nine-element vector representing the board. We store 2 (indicating Blank), 3 (indicating X), or 5 (indicating O). Turn: An integer indicating which move of the game about to be played. The 1st move will be indicated by 1, last by 9.

The Algorithm

The main algorithm uses three functions.

Make2: returns 5 if the center square of the board is blank i.e. if board[5]=2. Otherwise, this function returns any non-corner square (2, 4, 6 or 8).

Posswin(p): Returns 0 if player p can’t win on his next move; otherwise, it returns the number of the square that constitutes a winning move. This function will enable the program both to win and to block opponents win. This function operates by checking each of the rows, columns, and diagonals. By multiplying the values of each square together for an entire row (or column or diagonal), the possibility of a win can be checked. If the product is 18 (3 x 3 x 2), then X can win. If the product is 50 (5 x 5 x 2), then O can win. If a winning row (column or diagonal) is found, the blank square in it can be determined and the number of that square is returned by this function.

Go (n): makes a move in square n. this procedure sets board [n] to 3 if Turn is odd, or 5 if Turn is even. It also increments turn by one.

The algorithm has a built-in strategy for each move. It makes the odd numbered move if it plays X, the even-numbered move if it plays O.

Turn = 1    Go(1)   (upper left corner).
Turn = 2    If Board[5] is blank, Go(5), else Go(1).
Turn = 3    If Board[9] is blank, Go(9), else Go(3).
Turn = 4    If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).
Turn = 5    if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].
Turn = 6    If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).
Turn = 7    If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.
Turn = 8    if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.
Turn = 9    Same as Turn=7.

I have used it. Let me know how you guys feel.

How to get a list of sub-folders and their files, ordered by folder-names

In command prompt go to the main directory you want the list for ... and type the command tree /f

Any way to make a WPF textblock selectable?

Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.

<TextBox Background="Transparent"
         BorderThickness="0"
         Text="{Binding Text, Mode=OneWay}"
         IsReadOnly="True"
         TextWrapping="Wrap" />

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

Strings & VARCHAR.

  • Do not try storing phone numbers as actual numbers. it will ruin the formatting, remove preceding 0s and other undesirable things.

  • You may, if you choose to, restrict user inputs to just numeric values but even in that case, keep your backing persisted data as characters/strings and not numbers.

  • Be aware of the wider world and how their number lengths and formatting differ before you try to implement any sort of length restrictions, validations or masks (eg XXX-XXXX-XX).

  • Non numeric characters can be valid in phone numbers. A prime example being + as a replacement for 00 at the start of an international number.

Edited in from conversation in comments:

  • It is one of the bigger UI mistakes that phone numbers have anything to do with numerics. It is much better to think of and treat them like addresses, it is closer to what they actually are and represent than phone "numbers".

How to rename with prefix/suffix?

You can achieve a unix compatible multiple file rename (using wildcards) by creating a for loop:

for file in *; do
  mv $file new.${file%%}
done

Getting Current date, time , day in laravel

If you want date of today

use namespace

use Carbon\Carbon as time;

code ,

 $mytime=time::now();
 $date=$mytime->toRfc850String();
 $today= substr($date, 0, strrpos($date, ","));
 dd($today)

output , "Sunday"

How to preview git-pull without doing fetch?

What about cloning the repo elsewhere, and doing git log on both the real checkout and the fresh clone to see if you got the same thing.

Hibernate: How to set NULL query-parameter value with HQL?

Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:

setParameter("orderItemId", orderItemId, new LongType())

After that, I use the following where clause in my query:

where ((:orderItemId is null) OR (orderItem.id != :orderItemId))

As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.

Hope this helps!

The smallest difference between 2 Angles

Arithmetical (as opposed to algorithmic) solution:

angle = Pi - abs(abs(a1 - a2) - Pi);

How to export a CSV to Excel using Powershell

I am using excelcnv.exe to convert csv into xlsx and that seemed to work properly. You will have to change the directory to where your excelcnv is. If 32 bit, it goes to Program Files (x86)

Start-Process -FilePath 'C:\Program Files\Microsoft Office\root\Office16\excelcnv.exe' -ArgumentList "-nme -oice ""$xlsFilePath"" ""$xlsToxlsxPath"""

How to delete multiple rows in SQL where id = (x to y)

If you need to delete based on a list, you can use IN:

DELETE FROM your_table
WHERE id IN (value1, value2, ...);

If you need to delete based on the result of a query, you can also use IN:

DELETE FROM your_table
WHERE id IN (select aColumn from ...);

(Notice that the subquery must return only one column)

If you need to delete based on a range of values, either you use BETWEEN or you use inequalities:

DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;

or

DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

Create table (structure) from existing table

SELECT * INTO newtable
from Oldtable

How to multiply duration by integer?

In Go, you can multiply variables of same type, so you need to have both parts of the expression the same type.

The simplest thing you can do is casting an integer to duration before multiplying, but that would violate unit semantics. What would be multiplication of duration by duration in term of units?

I'd rather convert time.Millisecond to an int64, and then multiply it by the number of milliseconds, then cast to time.Duration:

time.Duration(int64(time.Millisecond) * int64(rand.Int31n(1000)))

This way any part of the expression can be said to have a meaningful value according to its type. int64(time.Millisecond) part is just a dimensionless value - the number of smallest units of time in the original value.

If walk a slightly simpler path:

time.Duration(rand.Int31n(1000)) * time.Millisecond

The left part of multiplication is nonsense - a value of type "time.Duration", holding something irrelevant to its type:

numberOfMilliseconds := 100
// just can't come up with a name for following:
someLHS := time.Duration(numberOfMilliseconds)
fmt.Println(someLHS)
fmt.Println(someLHS*time.Millisecond)

And it's not just semantics, there is actual functionality associated with types. This code prints:

100ns
100ms

Interestingly, the code sample here uses the simplest code, with the same misleading semantics of Duration conversion: https://golang.org/pkg/time/#Duration

seconds := 10

fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

maven "cannot find symbol" message unhelpful

I had the same issue with maven. It happens that my problem was, maven was generating the folders with differenc case names. I was expecting a .service.MyFile but in the target folder it was Service/MyFile and java is a case sensitive. It took me a few hours to find out, recommend you to check it out.

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ " in following files.

  • css/bootstrap.min.css
  • css/bootstrap.css

To fetch the file path in Linux use the command find / -name "\*bootstrap\*"

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Moment.js - How to convert date string into date?

Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');

Dec 4, 2020 4:58 PM

OtherFormats

moment.locale();         // en
moment().format('LT');   // 4:59 PM
moment().format('LTS');  // 4:59:47 PM
moment().format('L');    // 12/08/2020
moment().format('l');    // 12/8/2020
moment().format('LL');   // December 8, 2020
moment().format('ll');   // Dec 8, 2020
moment().format('LLL');  // December 8, 2020 4:59 PM
moment().format('lll');  // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM

Apply a function to every row of a matrix or a data frame

Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...). Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

How to return a string from a C++ function?

Assign something to your strings. This will definitely help.

Spring's overriding bean

An example from official spring manual:

<bean id="inheritedTestBean" abstract="true"
    class="org.springframework.beans.TestBean">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass"
      class="org.springframework.beans.DerivedTestBean"
      parent="inheritedTestBean" init-method="initialize">
  <property name="name" value="override"/>
  <!-- the age property value of 1 will be inherited from  parent -->
</bean>

Is that what you was looking for? Updated link

how to get multiple checkbox value using jquery

You can get them like this

$('#save_value').click(function() {
    $('.ads_Checkbox:checked').each(function() {
        alert($(this).val());
    });
});

jsfiddle

requestFeature() must be called before adding content

Well, just do what the error message tells you.

Don't call setContentView() before requestFeature().

Note:

As said in comments, for both ActionBarSherlock and AppCompat library, it's necessary to call requestFeature() before super.onCreate()

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

This will end up giving you an absolute file path that you can construct a file uri from

Why is my CSS style not being applied?

I know this is an old post but I thought I might add a thought for people who come across a similar problem. I'm assuming that you are using ASP.NET MVC since you mentioned site.css.

Check your Bundles.config file to see if you have BundleTable.EnableOptimizations = true; If you don't, then it can be your problem since this allows the program to be bundles and "minified". Depending on if you run in debug mode or not this could have an effect.

How to validate phone number using PHP?

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....

Take a look at this similar question to get some ideas.

Then there is E.164 which is a numbering standard recommendation from ITU-T

How to remove border from specific PrimeFaces p:panelGrid?

If BalusC answer doesn't work try this:

.companyHeaderGrid td {
     border-style: hidden !important;
}

Testing if a site is vulnerable to Sql Injection

SQL Injection can be done on any input the user can influence that isn't properly escaped before used in a query.

One example would be a get variable like this:

http//www.example.com/user.php?userid=5

Now, if the accompanying PHP code goes something like this:

$query = "SELECT username, password FROM users WHERE userid=" . $_GET['userid'];
// ...

You can easily use SQL injection here too:

http//www.example.com/user.php?userid=5 AND 1=2 UNION SELECT password,username FROM users WHERE usertype='admin'

(of course, the spaces will have to be replaced by %20, but this is more readable. Additionally, this is just an example making some more assumptions, but the idea should be clear.)

iPhone SDK on Windows (alternative solutions)

This really comes down to how much you value your time. As the other posters have mentioned, there are a couple of ways you can build iPhone apps without a Mac. However, you are jumping through serious hoops, and it'll be much more difficult and take longer than it would with the proper development chain.

You can buy a second-hand Mac Mini for a couple of hundred bucks on eBay. If you're serious about doing iPhone development you'll make this back in saved time very quickly.

PowerShell To Set Folder Permissions

Another example using PowerShell for set permissions (File / Directory) :

Verify permissions

Get-Acl "C:\file.txt" | fl *

Apply full permissions for everyone

$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"

Screenshots: enter image description here enter image description here

Hope this helps

copy all files and folders from one drive to another drive using DOS (command prompt)

Use robocopy. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy. (xcopy has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).

robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat

Note that using /purge on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /? for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b instead of /zb.

Need to ZIP an entire directory using Node.js

Since archiver is not compatible with the new version of webpack for a long time, I recommend using zip-lib.

var zl = require("zip-lib");

zl.archiveFolder("path/to/folder", "path/to/target.zip").then(function () {
    console.log("done");
}, function (err) {
    console.log(err);
});

Ineligible Devices section appeared in Xcode 6.x.x

I changed my deployment target to 7.1 the same as my iphone, and now I can run swift programs on it. It was on 8.0 and showed up as ineligible.

How to get the CPU Usage in C#?

This class automatically polls the counter every 1 seconds and is also thread safe:

public class ProcessorUsage
{
    const float sampleFrequencyMillis = 1000;

    protected object syncLock = new object();
    protected PerformanceCounter counter;
    protected float lastSample;
    protected DateTime lastSampleTime;

    /// <summary>
    /// 
    /// </summary>
    public ProcessorUsage()
    {
        this.counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public float GetCurrentValue()
    {
        if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
        {
            lock (syncLock)
            {
                if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
                {
                    lastSample = counter.NextValue();
                    lastSampleTime = DateTime.UtcNow;
                }
            }
        }

        return lastSample;
    }
}

How to convert Json array to list of objects in c#

Json Convert To C# Class = https://json2csharp.com/json-to-csharp

after the schema comes out

        WebClient client = new WebClient();

        client.Encoding = Encoding.UTF8;

        string myJSON = client.DownloadString("http://xxx/xx/xx.json");

        var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);

The biggest one of our mistakes is that we can't match the class structure with json.

This connection will do the process automatically. You will code it later ;) = https://json2csharp.com/json-to-csharp

that's it.

Ping with timestamp on Windows CLI

You can do this in Bash (e.g. Linux or WSL):

ping 10.0.0.1 | while read line; do echo `date` - $line; done

Although it doesn't give the statistics you usually get when you hit ^C at the end.

How to use jQuery to select a dropdown option?

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);

How to make a PHP SOAP call using the SoapClient class

There is an option to generate php5 objects with WsdlInterpreter class. See more here: https://github.com/gkwelding/WSDLInterpreter

for example:

require_once 'WSDLInterpreter-v1.0.0/WSDLInterpreter.php';
$wsdlLocation = '<your wsdl url>?wsdl';
$wsdlInterpreter = new WSDLInterpreter($wsdlLocation);
$wsdlInterpreter->savePHP('.');

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

I know this is an old question, but if you ever want ot fix the malformed '&' signs in your HTML. You can use code similar to this:

$page = file_get_contents('http://www.example.com');
$page = preg_replace('/\s+/', ' ', trim($page));
fixAmps($page, 0);
$dom->loadHTML($page);


function fixAmps(&$html, $offset) {
    $positionAmp = strpos($html, '&', $offset);
    $positionSemiColumn = strpos($html, ';', $positionAmp+1);

    $string = substr($html, $positionAmp, $positionSemiColumn-$positionAmp+1);

    if ($positionAmp !== false) { // If an '&' can be found.
        if ($positionSemiColumn === false) { // If no ';' can be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // Replace straight away.
        } else if (preg_match('/&(#[0-9]+|[A-Z|a-z|0-9]+);/', $string) === 0) { // If a standard escape cannot be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // This mean we need to escape the '&' sign.
            fixAmps($html, $positionAmp+5); // Recursive call from the new position.
        } else {
            fixAmps($html, $positionAmp+1); // Recursive call from the new position.
        }
    }
}

Remove all values within one list from another list?

a = range(1,10)
itemsToRemove = set([2, 3, 7])
b = filter(lambda x: x not in itemsToRemove, a)

or

b = [x for x in a if x not in itemsToRemove]

Don't create the set inside the lambda or inside the comprehension. If you do, it'll be recreated on every iteration, defeating the point of using a set at all.

Search text in fields in every table of a MySQL database

i got this to work. you just need to change the variables

$query ="SELECT `column_name` FROM `information_schema`.`columns` WHERE `table_schema`='" . $_SESSION['db'] . "' AND `table_name`='" . $table . "' ";
$stmt = $dbh->prepare($query);
$stmt->execute(); 
$columns = $stmt->fetchAll(PDO::FETCH_ASSOC);       

$query="SELECT name FROM `" . $database . "`.`" . $table . "` WHERE ( ";
foreach ( $columns as $column ) {
    $query .=" CONVERT( `" . $column['column_name'] . "` USING utf8 ) LIKE '%" . $search . "%' OR ";
}
$query = substr($query, 0, -3);
$query .= ")";

echo $query . "<br>";
$stmt=$dbh->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r ($results );
echo "</pre>";

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

rewrite a folder name using .htaccess

try:

RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.

See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/

There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php

to redirect from /folder1 to /apple try this:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]

to redirect and then rewrite just combine the above in the htaccess file:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

replace NULL with Blank value or Zero in sql server

You can use the COALESCE function to automatically return null values as 0. Syntax is as shown below:

SELECT COALESCE(total_amount, 0) from #Temp1

How to get Latitude and Longitude of the mobile device in android?

you can got Current latlng using this

`

  public class MainActivity extends ActionBarActivity {
  private LocationManager locationManager;
  private String provider;
  private MyLocationListener mylistener;
  private Criteria criteria;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


             locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
              // Define the criteria how to select the location provider
              criteria = new Criteria();
              criteria.setAccuracy(Criteria.ACCURACY_COARSE);   //default

              // user defines the criteria

              criteria.setCostAllowed(false); 
              // get the best provider depending on the criteria
              provider = locationManager.getBestProvider(criteria, false);

              // the last known location of this provider
              Location location = locationManager.getLastKnownLocation(provider);

              mylistener = new MyLocationListener();

              if (location != null) {
                  mylistener.onLocationChanged(location);
              } else {
                  // leads to the settings because there is no last known location
                  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                  startActivity(intent);
              }
              // location updates: at least 1 meter and 200millsecs change
              locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
            String a=""+location.getLatitude();
            Toast.makeText(getApplicationContext(), a, 222).show();

}

private class MyLocationListener implements LocationListener {

      @Override
      public void onLocationChanged(Location location) {
        // Initialize the location fields



          Toast.makeText(MainActivity.this,  ""+location.getLatitude()+location.getLongitude(),
                    Toast.LENGTH_SHORT).show()  

      }

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {
          Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
                    Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onProviderEnabled(String provider) {
          Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
            Toast.LENGTH_SHORT).show();

      }

      @Override
      public void onProviderDisabled(String provider) {
          Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
            Toast.LENGTH_SHORT).show();
      }
  }         

`

Calling async method synchronously

Most of the answers on this thread are either complex or will result in deadlock.

Following method is simple and it will avoid deadlock because we are waiting for the task to finish and only then getting its result-

var task = Task.Run(() => GenerateCodeAsync()); 
task.Wait();
string code = task.Result;

Furthermore, here is a reference to MSDN article that talks about exactly same thing- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/

Split a large pandas dataframe

You can use groupby, assuming you have an integer enumerated index:

import math
df = pd.DataFrame(dict(sample=np.arange(99)))
rows_per_subframe = math.ceil(len(df) / 4.)

subframes = [i[1] for i in df.groupby(np.arange(len(df))//rows_per_subframe)]

Note: groupby returns a tuple in which the 2nd element is the dataframe, thus the slightly complicated extraction.

>>> len(subframes), [len(i) for i in subframes]
(4, [25, 25, 25, 24])

What is the difference between tree depth and height?

height and depth of a tree is equal...

but height and depth of a node is not equal because...

the height is calculated by traversing from the given node to the deepest possible leaf.

depth is calculated from traversal from root to the given node.....

How do I create ColorStateList programmatically?

Bouncing off the answer by Jonathan Ellis, in Kotlin you can define a helper function to make the code a bit more idiomatic and easier to read, so you can write this instead:

val colorList = colorStateListOf(
    intArrayOf(-android.R.attr.state_enabled) to Color.BLACK,
    intArrayOf(android.R.attr.state_enabled) to Color.RED,
)

colorStateListOf can be implemented like this:

fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
    val (states, colors) = mapping.unzip()
    return ColorStateList(states.toTypedArray(), colors.toIntArray())
}

I also have:

fun colorStateListOf(@ColorInt color: Int): ColorStateList {
    return ColorStateList.valueOf(color)
}

So that I can call the same function name, no matter if it's a selector or single color.

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

If Android Studio directly opening your project instead of setup window, then just close the windows of all projects. Now you will able to see the startup window. If SDK is missing then it will provide option to download SDK and other required tools.

It works for me.

Checking if an object is a given type in Swift

for swift4:

if obj is MyClass{
    // then object type is MyClass Type
}

What does the function then() mean in JavaScript?

I am about 8 years late, well...anyways, I don't really know what then() does but maybe MDN might have an answer. Actually, I might actually understand it a little more.

This will show you all the information (hopefully), you need. Unless someone already posted this link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

The format is promise.prototype.then() The promise and prototype are kind of like variables but not like variables in javascript, I mean like other things go there like navigator.getBattery().then() where this one actually exists but is barely used on the web, this one shows statuses about the battery of the device, more information and more on MDN if you are curious.

An unhandled exception occurred during the execution of the current web request. ASP.NET

  1. If you are facing this problem (Enter windows + R) an delete temp(%temp%)and windows temp.
  2. Some file is not deleted that time stop IIS(Internet information service) and delete that all remaining files .

Check your problem is solved.

Why does PEP-8 specify a maximum line length of 79 characters?

Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.

Writing a dictionary to a text file?

I do it like this in python 3:

with open('myfile.txt', 'w') as f:
    print(mydictionary, file=f)

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

c++ Read from .csv file

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M

Try this

0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M


while(file.good())
{

    getline(file, ID, ',');
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero) ; \\ diff
    cout << "Sexo: " <<  genero;\\diff


}

React - How to pass HTML tags in props?

This question has already a lot of answers, but I had was doing something wrong related to this and I think is worth sharing:

I had something like this:

export default function Features() {
  return (
    <Section message={<p>This is <strong>working</strong>.</p>} />
  }
}

but the massage was longer than that, so I tried using something like this:

const message = () => <p>This longer message is <strong>not</strong> working.</p>;

export default function Features() {
  return (
    <Section message={message} />
  }
}

It took me a while to realize that I was missing the () in the function call.

Not working

<Section message={message} />

Working

<Section message={message()} />

maybe this helps you, as it did to me!

What does 'IISReset' do?

Editing the web.config file or updating a DLL in the bin folder just recycles the worker process for that application, not the whole pool.

Multiple files upload (Array) with CodeIgniter 2.0

I have used below code in my custom library
call that from my controller like below,

function __construct() {<br />
   &nbsp;&nbsp;&nbsp; parent::__construct();<br />
   &nbsp;&nbsp;&nbsp;   $this->load->library('CommonMethods');<br />
}<br />

$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />

// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);

/**
 * do_upload_multiple_files - Multiple Methods
 * @param type $fieldName
 * @param type $options
 * @return type
 */
public function do_upload_multiple_files($fieldName, $options) {

    $response = array();
    $files = $_FILES;
    $cpt = count($_FILES[$fieldName]['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
        $_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
        $_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
        $_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
        $_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];    

        $this->CI->load->library('upload');
        $this->CI->upload->initialize($options);

        //upload the image
        if (!$this->CI->upload->do_upload($fieldName)) {
            $response['erros'][] = $this->CI->upload->display_errors();
        } else {
            $response['result'][] = $this->CI->upload->data();
        }
    }

    return $response;
}