Programs & Examples On #Assembly.reflectiononly

How to Load an Assembly to AppDomain with all references recursively?

I have had to do this several times and have researched many different solutions.

The solution I find in most elegant and easy to accomplish can be implemented as such.

1. Create a project that you can create a simple interface

the interface will contain signatures of any members you wish to call.

public interface IExampleProxy
{
    string HelloWorld( string name );
}

Its important to keep this project clean and lite. It is a project that both AppDomain's can reference and will allow us to not reference the Assembly we wish to load in seprate domain from our client assembly.

2. Now create project that has the code you want to load in seperate AppDomain.

This project as with the client proj will reference the proxy proj and you will implement the interface.

public interface Example : MarshalByRefObject, IExampleProxy
{
    public string HelloWorld( string name )
    {
        return $"Hello '{ name }'";
    }
}

3. Next, in the client project, load code in another AppDomain.

So, now we create a new AppDomain. Can specify the base location for assembly references. Probing will check for dependent assemblies in GAC and in current directory and the AppDomain base loc.

// set up domain and create
AppDomainSetup domaininfo = new AppDomainSetup
{
    ApplicationBase = System.Environment.CurrentDirectory
};

Evidence adevidence = AppDomain.CurrentDomain.Evidence;

AppDomain exampleDomain = AppDomain.CreateDomain("Example", adevidence, domaininfo);

// assembly ant data names
var assemblyName = "<AssemblyName>, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null|<keyIfSigned>";
var exampleTypeName = "Example";

// Optional - get a reflection only assembly type reference
var @type = Assembly.ReflectionOnlyLoad( assemblyName ).GetType( exampleTypeName ); 

// create a instance of the `Example` and assign to proxy type variable
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( assemblyName, exampleTypeName );

// Optional - if you got a type ref
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( @type.Assembly.Name, @type.Name );    

// call any members you wish
var stringFromOtherAd = proxy.HelloWorld( "Tommy" );

// unload the `AppDomain`
AppDomain.Unload( exampleDomain );

if you need to, there are a ton of different ways to load an assembly. You can use a different way with this solution. If you have the assembly qualified name then I like to use the CreateInstanceAndUnwrap since it loads the assembly bytes and then instantiates your type for you and returns an object that you can simple cast to your proxy type or if you not that into strongly-typed code you could use the dynamic language runtime and assign the returned object to a dynamic typed variable then just call members on that directly.

There you have it.

This allows to load an assembly that your client proj doesnt have reference to in a seperate AppDomain and call members on it from client.

To test, I like to use the Modules window in Visual Studio. It will show you your client assembly domain and what all modules are loaded in that domain as well your new app domain and what assemblies or modules are loaded in that domain.

The key is to either make sure you code either derives MarshalByRefObject or is serializable.

`MarshalByRefObject will allow you to configure the lifetime of the domain its in. Example, say you want the domain to destroy if the proxy hasnt been called in 20 minutes.

I hope this helps.

Private vs Protected - Visibility Good-Practice Concern

Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo" you can see it (you class only single class).

How to get all subsets of a set? (powerset)

You can do it like this:

def powerset(x):
    m=[]
    if not x:
        m.append(x)
    else:
        A = x[0]
        B = x[1:]
        for z in powerset(B):
            m.append(z)
            r = [A] + z
            m.append(r)
    return m

print(powerset([1, 2, 3, 4]))

Output:

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

How to get the selected value from RadioButtonList?

Using your radio button's ID, try rb.SelectedValue.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Short answer:

There is no difference in semantic.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Further reading:

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to method:

Annotation for mapping HTTP GET requests onto specific handler methods.


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

Removing numbers from string

Just a few (others have suggested some of these)

Method 1:

''.join(i for i in myStr if not i.isdigit())

Method 2:

def removeDigits(s):
    answer = []
    for char in s:
        if not char.isdigit():
            answer.append(char)
    return ''.join(char)

Method 3:

''.join(filter(lambda x: not x.isdigit(), mystr))

Method 4:

nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)

Method 5:

''.join(i for i in mystr if ord(i) not in range(48, 58))

ImportError: No module named pandas

As of Dec 2020, I had the same issue when installing python v 3.8.6 via pyenv. So, I started by:

  1. Installing pyenv via homebrew brew install pyenv
  2. Install xz compiling package via brew install xz
  3. pyenv install 3.8.6 pick the required version
  4. pyenv global 3.8.6 make this version as global
  5. python -m pip install -U pip to upgrade pip
  6. pip install virtualenv

After that, I initialized my new env, installed pandas via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!

Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.

merge one local branch into another local branch

To merge one branch into another, such as merging "feature_x" branch into "master" branch:

git checkout master

git merge feature_x

This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.

How to convert a PIL Image into a numpy array?

The example, I have used today:

import PIL
import numpy
from PIL import Image

def resize_image(numpy_array_image, new_height):
    # convert nympy array image to PIL.Image
    image = Image.fromarray(numpy.uint8(numpy_array_image))
    old_width = float(image.size[0])
    old_height = float(image.size[1])
    ratio = float( new_height / old_height)
    new_width = int(old_width * ratio)
    image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
    # convert PIL.Image into nympy array back again
    return array(image)

No newline after div?

This works like magic, use it in the CSS file on the div you want to have on the new line:

.div_class {
    clear: left;
}

Or declare it in the html:

<div style="clear: left">
     <!-- Content... -->
</div>

Getting View's coordinates relative to the root layout

You can use `

view.getLocationOnScreen(int[] location)

;` to get location of your view correctly.

But there is a catch if you use it before layout has been inflated you will get wrong position.

Solution to this problem is adding ViewTreeObserver like this :-

Declare globally the array to store x y position of your view

 int[] img_coordinates = new int[2];

and then add ViewTreeObserver on your parent layout to get callback for layout inflation and only then fetch position of view otherwise you will get wrong x y coordinates

  // set a global layout listener which will be called when the layout pass is completed and the view is drawn
            parentViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        public void onGlobalLayout() {
                            //Remove the listener before proceeding
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                parentViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            } else {
                                parentViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }

                            // measure your views here
                            fab.getLocationOnScreen(img_coordinates);
                        }
                    }
            );

and then use it like this

xposition = img_coordinates[0];
yposition =  img_coordinates[1];

Is it possible to move/rename files in Git and maintain their history?

Yes

  1. You convert the commit history of files into email patches using git log --pretty=email
  2. You reorganize these files in new directories and rename them
  3. You convert back these files (emails) to Git commits to keep the history using git am.

Limitation

  • Tags and branches are not kept
  • History is cut on path file rename (directory rename)

Step by step explanation with examples

1. Extract history in email format

Example: Extract history of file3, file4 and file5

my_repo
+-- dirA
¦   +-- file1
¦   +-- file2
+-- dirB            ^
¦   +-- subdir      | To be moved
¦   ¦   +-- file3   | with history
¦   ¦   +-- file4   | 
¦   +-- file5       v
+-- dirC
    +-- file6
    +-- file7

Set/clean the destination

export historydir=/tmp/mail/dir       # Absolute path
rm -rf "$historydir"    # Caution when cleaning the folder

Extract history of each file in email format

cd my_repo/dirB
find -name .git -prune -o -type d -o -exec bash -c 'mkdir -p "$historydir/${0%/*}" && git log --pretty=email -p --stat --reverse --full-index --binary -- "$0" > "$historydir/$0"' {} ';'

Unfortunately option --follow or --find-copies-harder cannot be combined with --reverse. This is why history is cut when file is renamed (or when a parent directory is renamed).

Temporary history in email format:

/tmp/mail/dir
    +-- subdir
    ¦   +-- file3
    ¦   +-- file4
    +-- file5

Dan Bonachea suggests to invert the loops of the git log generation command in this first step: rather than running git log once per file, run it exactly once with a list of files on the command line and generate a single unified log. This way commits that modify multiple files remain a single commit in the result, and all the new commits maintain their original relative order. Note this also requires changes in second step below when rewriting filenames in the (now unified) log.


2. Reorganize file tree and update filenames

Suppose you want to move these three files in this other repo (can be the same repo).

my_other_repo
+-- dirF
¦   +-- file55
¦   +-- file56
+-- dirB              # New tree
¦   +-- dirB1         # from subdir
¦   ¦   +-- file33    # from file3
¦   ¦   +-- file44    # from file4
¦   +-- dirB2         # new dir
¦        +-- file5    # from file5
+-- dirH
    +-- file77

Therefore reorganize your files:

cd /tmp/mail/dir
mkdir -p dirB/dirB1
mv subdir/file3 dirB/dirB1/file33
mv subdir/file4 dirB/dirB1/file44
mkdir -p dirB/dirB2
mv file5 dirB/dirB2

Your temporary history is now:

/tmp/mail/dir
    +-- dirB
        +-- dirB1
        ¦   +-- file33
        ¦   +-- file44
        +-- dirB2
             +-- file5

Change also filenames within the history:

cd "$historydir"
find * -type f -exec bash -c 'sed "/^diff --git a\|^--- a\|^+++ b/s:\( [ab]\)/[^ ]*:\1/$0:g" -i "$0"' {} ';'

3. Apply new history

Your other repo is:

my_other_repo
+-- dirF
¦   +-- file55
¦   +-- file56
+-- dirH
    +-- file77

Apply commits from temporary history files:

cd my_other_repo
find "$historydir" -type f -exec cat {} + | git am --committer-date-is-author-date

--committer-date-is-author-date preserves the original commit time-stamps (Dan Bonachea's comment).

Your other repo is now:

my_other_repo
+-- dirF
¦   +-- file55
¦   +-- file56
+-- dirB
¦   +-- dirB1
¦   ¦   +-- file33
¦   ¦   +-- file44
¦   +-- dirB2
¦        +-- file5
+-- dirH
    +-- file77

Use git status to see amount of commits ready to be pushed :-)


Extra trick: Check renamed/moved files within your repo

To list the files having been renamed:

find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow {} ';' | grep '=>'

More customizations: You can complete the command git log using options --find-copies-harder or --reverse. You can also remove the first two columns using cut -f3- and grepping complete pattern '{.* => .*}'.

find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow --find-copies-harder --reverse {} ';' | cut -f3- | grep '{.* => .*}'

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

How to set value in @Html.TextBoxFor in Razor syntax?

The problem is that you are using a lower case v.

You need to set it to Value and it should fix your issue:

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

Test if a string contains any of the strings from an array

If you use Java 8 or above, you can rely on the Stream API to do such thing:

public static boolean containsItemFromArray(String inputString, String[] items) {
    // Convert the array of String items as a Stream
    // For each element of the Stream call inputString.contains(element)
    // If you have any match returns true, false otherwise
    return Arrays.stream(items).anyMatch(inputString::contains);
}

Assuming that you have a big array of big String to test you could also launch the search in parallel by calling parallel(), the code would then be:

return Arrays.stream(items).parallel().anyMatch(inputString::contains); 

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

UIView Infinite 360 degree rotation animation?

Swift 3 :

 var rotationAnimation = CABasicAnimation()
     rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
     rotationAnimation.toValue = NSNumber(value: (M_PI * 2.0))
     rotationAnimation.duration = 2.0
     rotationAnimation.isCumulative = true
     rotationAnimation.repeatCount = 10.0
     view.layer.add(rotationAnimation, forKey: "rotationAnimation")

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

How to insert text into the textarea at the current cursor position?

This snippet could help you with it in a few lines of jQuery 1.9+: http://jsfiddle.net/4MBUG/2/

$('input[type=button]').on('click', function() {
    var cursorPos = $('#text').prop('selectionStart');
    var v = $('#text').val();
    var textBefore = v.substring(0,  cursorPos);
    var textAfter  = v.substring(cursorPos, v.length);

    $('#text').val(textBefore + $(this).val() + textAfter);
});

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

using lodash .groupBy. how to add your own keys for grouped output?

Here is an updated version using lodash 4 and ES6

const result = _.chain(data)
    .groupBy("color")
    .toPairs()
    .map(pair => _.zipObject(['color', 'users'], pair))
    .value();

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

Multiplying Two Columns in SQL Server

This code is used to multiply the values of one column

select exp(sum(log(column))) from table

javascript find and remove object in array based on key value

I agree with the answers, a simple way if you want to find an object by id and remove it is simply like below code.

   var obj = JSON.parse(data);
   var newObj = obj.filter(item=>item.Id!=88);
       

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How to send email to multiple address using System.Net.Mail

MailAddress fromAddress = new MailAddress  (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
    Host = host, Port = port,
    enabHost = "smtp.gmail.com",
    Port = 25,
    EnableSsl = true,
    UseDefaultCredentials = true,
    Credentials = new  NetworkCredentials (fromMail, password)
};
smtp.send(message);

JQuery .on() method with multiple event handlers to one selector

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

How to save DataFrame directly to Hive?

you need to have/create a HiveContext

import org.apache.spark.sql.hive.HiveContext;

HiveContext sqlContext = new org.apache.spark.sql.hive.HiveContext(sc.sc());

Then directly save dataframe or select the columns to store as hive table

df is dataframe

df.write().mode("overwrite").saveAsTable("schemaName.tableName");

or

df.select(df.col("col1"),df.col("col2"), df.col("col3")) .write().mode("overwrite").saveAsTable("schemaName.tableName");

or

df.write().mode(SaveMode.Overwrite).saveAsTable("dbName.tableName");

SaveModes are Append/Ignore/Overwrite/ErrorIfExists

I added here the definition for HiveContext from Spark Documentation,

In addition to the basic SQLContext, you can also create a HiveContext, which provides a superset of the functionality provided by the basic SQLContext. Additional features include the ability to write queries using the more complete HiveQL parser, access to Hive UDFs, and the ability to read data from Hive tables. To use a HiveContext, you do not need to have an existing Hive setup, and all of the data sources available to a SQLContext are still available. HiveContext is only packaged separately to avoid including all of Hive’s dependencies in the default Spark build.


on Spark version 1.6.2, using "dbName.tableName" gives this error:

org.apache.spark.sql.AnalysisException: Specifying database name or other qualifiers are not allowed for temporary tables. If the table name has dots (.) in it, please quote the table name with backticks ().`

Selecting with complex criteria from pandas.DataFrame

You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)

df[['A']][df.B.gt(50) & df.C.ne(900)]

df[['A']] will give you back column A in DataFrame format.

pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

find out the lib depends on the support v4, and exclude it.

code in build.gradle is like this:

androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.1') {
    // http://stackoverflow.com/a/30931887/5210
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude module: 'recyclerview-v7'
}

In my situation, the lib 'espresso' has a jar called support-v4 and in my project 'app' have the same support-v4, exclude the support-v4 when import espresso.

PS: it seems compile project can not work with the exclude

How to check file input size with jQuery?

This code:

$("#yourFileInput")[0].files[0].size;

Returns the file size for an form input.

On FF 3.6 and later this code should be:

$("#yourFileInput")[0].files[0].fileSize;

Replace non ASCII character from string

FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:

String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");

=> will produce "oau"

That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.

receiver type *** for instance message is a forward declaration

I got this sort of message when I had two files that depended on each other. The tricky thing here is that you'll get a circular reference if you just try to import each other (class A imports class B, class B imports class A) from their header files. So what you would do is instead place a forward (@class A) declaration in one of the classes' (class B's) header file. However, when attempting to use an ivar of class A within the implementation of class B, this very error comes up, merely adding an #import "A.h" in the .m file of class B fixed the problem for me.

PHP Fatal error: Class 'PDO' not found

I had the same problem on GoDaddy. I added the extension=pdo.so to php.ini, still didn't work. And then only one thing came to my mind: Permissions

Before uploading the file, kill all PHP processes(cPanel->PHP Processes).

The problem was that with the file permissions, it was set to 0644 and was not executable . You need to set the file permission at least 0755.

Permissions

How do I set default values for functions parameters in Matlab?

There isn't a direct way to do this like you've attempted.

The usual approach is to use "varargs" and check against the number of arguments. Something like:

function f(arg1, arg2, arg3)

  if nargin < 3
    arg3 =   'some default'
  end

end

There are a few fancier things you can do with isempty, etc., and you might want to look at Matlab central for some packages that bundle these sorts of things.

You might have a look at varargin, nargchk, etc. They're useful functions for this sort of thing. varargs allow you to leave a variable number of final arguments, but this doesn't get you around the problem of default values for some/all of them.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

WPF MVVM ComboBox SelectedItem or SelectedValue not working

The type of the SelectedValuePath and the SelectedValue must be EXACTLY the same.

If for example the type of SelectedValuePath is Int16 and the type of the property that binds to SelectedValue is int it will not work.

I spend hours to find that, and that's why I am answering here after so much time the question was asked. Maybe another poor guy like me with the same problem can see it.

AngularJS - Any way for $http.post to send request parameters instead of JSON?

Modify the default headers:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

Then use JQuery's $.param method:

var payload = $.param({key: value});
$http.post(targetURL, payload);

PHP Warning Permission denied (13) on session_start()

It seems that you don't have WRITE permission on /tmp.

Edit the configuration variable session.save_path with the function session_save_path() to 1 directory above public_html (so external users wouldn't access the info).

Combining node.js and Python

I've had a lot of success using thoonk.js along with thoonk.py. Thoonk leverages Redis (in-memory key-value store) to give you feed (think publish/subscribe), queue and job patterns for communication.

Why is this better than unix sockets or direct tcp sockets? Overall performance may be decreased a little, however Thoonk provides a really simple API that simplifies having to manually deal with a socket. Thoonk also helps make it really trivial to implement a distributed computing model that allows you to scale your python workers to increase performance, since you just spin up new instances of your python workers and connect them to the same redis server.

Regex lookahead, lookbehind and atomic groups

Examples

Given the string foobarbarfoo:

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)

You can also combine them:

(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

Definitions

Look ahead positive (?=)

Find expression A where expression B follows:

A(?=B)

Look ahead negative (?!)

Find expression A where expression B does not follow:

A(?!B)

Look behind positive (?<=)

Find expression A where expression B precedes:

(?<=B)A

Look behind negative (?<!)

Find expression A where expression B does not precede:

(?<!B)A

Atomic groups (?>)

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

  • (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

  • (foo|foot)s applied to foots will:

    1. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
    2. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.

Some resources

Online testers

How to properly export an ES6 class in Node 4?

Sometimes I need to declare multiple classes in one file, or I want to export base classes and keep their names exported because of my JetBrains editor understands that better. I just use

global.MyClass = class MyClass { ... };

And somewhere else:

require('baseclasses.js');
class MySubclass extends MyClass() { ... }

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

How I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

Many time this error is caused when you update a product in your custom module's observer as shown below.

class [NAMESPACE]_[MODULE NAME]_Model_Observer
{
    /**
     * Flag to stop observer executing more than once
     *
     * @var static bool
     */
    static protected $_singletonFlag = false;

    public function saveProductData(Varien_Event_Observer $observer)
    {
        if (!self::$_singletonFlag) {
            self::$_singletonFlag = true;

            $product = $observer->getEvent()->getProduct();
             //do stuff to the $product object
            // $product->save();  // commenting out this line prevents the error
            $product->getResource()->save($product);
    }
} 

Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product) instead of $product->save()

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

Parsing JSON in Excel VBA

To parse JSON in VBA without adding a huge library to your workbook project, I created the following solution. It's extremely fast and stores all of the keys and values in a dictionary for easy access:

Function ParseJSON(json$, Optional key$ = "obj") As Object
    p = 1
    token = Tokenize(json)
    Set dic = CreateObject("Scripting.Dictionary")
    If token(p) = "{" Then ParseObj key Else ParseArr key
    Set ParseJSON = dic
End Function

Function ParseObj(key$)
    Do: p = p + 1
        Select Case token(p)
            Case "]"
            Case "[":  ParseArr key
            Case "{"
                       If token(p + 1) = "}" Then
                           p = p + 1
                           dic.Add key, "null"
                       Else
                           ParseObj key
                       End If
            
            Case "}":  key = ReducePath(key): Exit Do
            Case ":":  key = key & "." & token(p - 1)
            Case ",":  key = ReducePath(key)
            Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
        End Select
    Loop
End Function

Function ParseArr(key$)
    Dim e&
    Do: p = p + 1
        Select Case token(p)
            Case "}"
            Case "{":  ParseObj key & ArrayID(e)
            Case "[":  ParseArr key
            Case "]":  Exit Do
            Case ":":  key = key & ArrayID(e)
            Case ",":  e = e + 1
            Case Else: dic.Add key & ArrayID(e), token(p)
        End Select
    Loop
End Function

The code above does use a few helper functions, but the above is the meat of it.

The strategy used here is to employ a recursive tokenizer. I found it interesting enough to write an article about this solution on Medium. It explains the details.

Here is the full (yet surprisingly short) code listing, including all of the helper functions:

'-------------------------------------------------------------------
' VBA JSON Parser
'-------------------------------------------------------------------
Option Explicit
Private p&, token, dic
Function ParseJSON(json$, Optional key$ = "obj") As Object
    p = 1
    token = Tokenize(json)
    Set dic = CreateObject("Scripting.Dictionary")
    If token(p) = "{" Then ParseObj key Else ParseArr key
    Set ParseJSON = dic
End Function
Function ParseObj(key$)
    Do: p = p + 1
        Select Case token(p)
            Case "]"
            Case "[":  ParseArr key
            Case "{"
                       If token(p + 1) = "}" Then
                           p = p + 1
                           dic.Add key, "null"
                       Else
                           ParseObj key
                       End If
            
            Case "}":  key = ReducePath(key): Exit Do
            Case ":":  key = key & "." & token(p - 1)
            Case ",":  key = ReducePath(key)
            Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
        End Select
    Loop
End Function
Function ParseArr(key$)
    Dim e&
    Do: p = p + 1
        Select Case token(p)
            Case "}"
            Case "{":  ParseObj key & ArrayID(e)
            Case "[":  ParseArr key
            Case "]":  Exit Do
            Case ":":  key = key & ArrayID(e)
            Case ",":  e = e + 1
            Case Else: dic.Add key & ArrayID(e), token(p)
        End Select
    Loop
End Function
'-------------------------------------------------------------------
' Support Functions
'-------------------------------------------------------------------
Function Tokenize(s$)
    Const Pattern = """(([^""\\]|\\.)*)""|[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|\w+|[^\s""']+?"
    Tokenize = RExtract(s, Pattern, True)
End Function
Function RExtract(s$, Pattern, Optional bGroup1Bias As Boolean, Optional bGlobal As Boolean = True)
  Dim c&, m, n, v
  With CreateObject("vbscript.regexp")
    .Global = bGlobal
    .MultiLine = False
    .IgnoreCase = True
    .Pattern = Pattern
    If .TEST(s) Then
      Set m = .Execute(s)
      ReDim v(1 To m.Count)
      For Each n In m
        c = c + 1
        v(c) = n.value
        If bGroup1Bias Then If Len(n.submatches(0)) Or n.value = """""" Then v(c) = n.submatches(0)
      Next
    End If
  End With
  RExtract = v
End Function
Function ArrayID$(e)
    ArrayID = "(" & e & ")"
End Function
Function ReducePath$(key$)
    If InStr(key, ".") Then ReducePath = Left(key, InStrRev(key, ".") - 1)
End Function
Function ListPaths(dic)
    Dim s$, v
    For Each v In dic
        s = s & v & " --> " & dic(v) & vbLf
    Next
    Debug.Print s
End Function
Function GetFilteredValues(dic, match)
    Dim c&, i&, v, w
    v = dic.keys
    ReDim w(1 To dic.Count)
    For i = 0 To UBound(v)
        If v(i) Like match Then
            c = c + 1
            w(c) = dic(v(i))
        End If
    Next
    ReDim Preserve w(1 To c)
    GetFilteredValues = w
End Function
Function GetFilteredTable(dic, cols)
    Dim c&, i&, j&, v, w, z
    v = dic.keys
    z = GetFilteredValues(dic, cols(0))
    ReDim w(1 To UBound(z), 1 To UBound(cols) + 1)
    For j = 1 To UBound(cols) + 1
         z = GetFilteredValues(dic, cols(j - 1))
         For i = 1 To UBound(z)
            w(i, j) = z(i)
         Next
    Next
    GetFilteredTable = w
End Function
Function OpenTextFile$(f)
    With CreateObject("ADODB.Stream")
        .Charset = "utf-8"
        .Open
        .LoadFromFile f
        OpenTextFile = .ReadText
    End With
End Function

How to generate a git patch for a specific commit?

If you want to be sure the (single commit) patch will be applied on top of a specific commit, you can use the new git 2.9 (June 2016) option git format-patch --base

git format-patch --base=COMMIT_VALUE~ -M -C COMMIT_VALUE~..COMMIT_VALUE

# or
git format-patch --base=auto -M -C COMMIT_VALUE~..COMMIT_VALUE

# or
git config format.useAutoBase true
git format-patch -M -C COMMIT_VALUE~..COMMIT_VALUE

See commit bb52995, commit 3de6651, commit fa2ab86, commit ded2c09 (26 Apr 2016) by Xiaolong Ye (``).
(Merged by Junio C Hamano -- gitster -- in commit 72ce3ff, 23 May 2016)

format-patch: add '--base' option to record base tree info

Maintainers or third party testers may want to know the exact base tree the patch series applies to. Teach git format-patch a '--base' option to record the base tree info and append it at the end of the first message (either the cover letter or the first patch in the series).

The base tree info consists of the "base commit", which is a well-known commit that is part of the stable part of the project history everybody else works off of, and zero or more "prerequisite patches", which are well-known patches in flight that is not yet part of the "base commit" that need to be applied on top of "base commit" in topological order before the patches can be applied.

The "base commit" is shown as "base-commit: " followed by the 40-hex of the commit object name.
A "prerequisite patch" is shown as "prerequisite-patch-id: " followed by the 40-hex "patch id", which can be obtained by passing the patch through the "git patch-id --stable" command.


Git 2.23 (Q3 2019) will improve that, because the "--base" option of "format-patch" computed the patch-ids for prerequisite patches in an unstable way, which has been updated to compute in a way that is compatible with "git patch-id --stable".

See commit a8f6855, commit 6f93d26 (26 Apr 2019) by Stephen Boyd (akshayka).
(Merged by Junio C Hamano -- gitster -- in commit 8202d12, 13 Jun 2019)

format-patch: make --base patch-id output stable

We weren't flushing the context each time we processed a hunk in the patch-id generation code in diff.c, but we were doing that when we generated "stable" patch-ids with the 'patch-id' tool.

Let's port that similar logic over from patch-id.c into diff.c so we can get the same hash when we're generating patch-ids for 'format-patch --base=' types of command invocations.


Before Git 2.24 (Q4 2019), "git format-patch -o <outdir>" did an equivalent of "mkdir <outdir>" not "mkdir -p <outdir>", which is being corrected.

See commit edefc31 (11 Oct 2019) by Bert Wesarg (bertwesarg).
(Merged by Junio C Hamano -- gitster -- in commit f1afbb0, 18 Oct 2019)

format-patch: create leading components of output directory

Signed-off-by: Bert Wesarg

'git format-patch -o ' did an equivalent of 'mkdir <outdir>' not 'mkdir -p <outdir>', which is being corrected.

Avoid the usage of 'adjust_shared_perm' on the leading directories which may have security implications. Achieved by temporarily disabling of 'config.sharedRepository' like 'git init' does.


With Git 2.25 (Q1 2020), "git rebase" did not work well when format.useAutoBase configuration variable is set, which has been corrected.

See commit cae0bc0, commit 945dc55, commit 700e006, commit a749d01, commit 0c47e06 (04 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 71a7de7, 16 Dec 2019)

rebase: fix format.useAutoBase breakage

Reported-by: Christian Biesinger
Signed-off-by: Denton Liu

With format.useAutoBase = true, running rebase resulted in an error:

fatal: failed to get upstream, if you want to record base commit automatically,
please use git branch --set-upstream-to to track a remote branch.
Or you could specify base commit by --base=<base-commit-id> manually
error:
git encountered an error while preparing the patches to replay
these revisions:

ede2467cdedc63784887b587a61c36b7850ebfac..d8f581194799ae29bf5fa72a98cbae98a1198b12

As a result, git cannot rebase them.

Fix this by always passing --no-base to format-patch from rebase so that the effect of format.useAutoBase is negated.


With Git 2.29 (Q4 2020), "git format-patch"(man) learns to take "whenAble" as a possible value for the format.useAutoBase configuration variable to become no-op when the automatically computed base does not make sense.

See commit 7efba5f (01 Oct 2020) by Jacob Keller (jacob-keller).
(Merged by Junio C Hamano -- gitster -- in commit 5f8c70a, 05 Oct 2020)

format-patch: teach format.useAutoBase "whenAble" option

Signed-off-by: Jacob Keller

The format.useAutoBase configuration option exists to allow users to enable '--base=auto' for format-patch by default.

This can sometimes lead to poor workflow, due to unexpected failures when attempting to format an ancient patch:

$ git format-patch -1 <an old commit>
fatal: base commit shouldn't be in revision list  

This can be very confusing, as it is not necessarily immediately obvious that the user requested a --base (since this was in the configuration, not on the command line).

We do want --base=auto to fail when it cannot provide a suitable base, as it would be equally confusing if a formatted patch did not include the base information when it was requested.

Teach format.useAutoBase a new mode, "whenAble".

This mode will cause format-patch to attempt to include a base commit when it can. However, if no valid base commit can be found, then format-patch will continue formatting the patch without a base commit.

In order to avoid making yet another branch name unusable with --base, do not teach --base=whenAble or --base=whenable.

Instead, refactor the base_commit option to use a callback, and rely on the global configuration variable auto_base.

This does mean that a user cannot request this optional base commit generation from the command line. However, this is likely not too valuable. If the user requests base information manually, they will be immediately informed of the failure to acquire a suitable base commit. This allows the user to make an informed choice about whether to continue the format.

Add tests to cover the new mode of operation for --base.

git config now includes in its man page:

format-patch by default.
Can also be set to "whenAble" to allow enabling --base=auto if a suitable base is available, but to skip adding base info otherwise without the format dying.


With Git 2.30 (Q1 2021), "git format-patch --output=there"(man) did not work as expected and instead crashed.

The option is now supported.

See commit dc1672d, commit 1e1693b, commit 4c6f781 (04 Nov 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 5edc8bd, 18 Nov 2020)

format-patch: support --output option

Reported-by: Johannes Postler
Signed-off-by: Jeff King

We've never intended to support diff's --output option in format-patch. And until baa4adc66a (parse-options: disable option abbreviation with PARSE_OPT_KEEP_UNKNOWN, 2019-01-27, Git v2.22.0-rc0), it was impossible to trigger. We first parse the format-patch options before handing the remainder off to setup_revisions().
Before that commit, we'd accept "--output=foo" as an abbreviation for "--output-directory=foo". But afterwards, we don't check abbreviations, and --output gets passed to the diff code.

This results in nonsense behavior and bugs. The diff code will have opened a filehandle at rev.diffopt.file, but we'll overwrite that with our own handles that we open for each individual patch file. So the --output file will always just be empty. But worse, the diff code also sets rev.diffopt.close_file, so log_tree_commit() will close the filehandle itself. And then the main loop in cmd_format_patch() will try to close it again, resulting in a double-free.

The simplest solution would be to just disallow --output with format-patch, as nobody ever intended it to work. However, we have accidentally documented it (because format-patch includes diff-options). And it does work with "git log"(man) , which writes the whole output to the specified file. It's easy enough to make that work for format-patch, too: it's really the same as --stdout, but pointed at a specific file.

We can detect the use of the --output option by the "close_file" flag (note that we can't use rev.diffopt.file, since the diff setup will otherwise set it to stdout). So we just need to unset that flag, but don't have to do anything else. Our situation is otherwise exactly like --stdout (note that we don't fclose() the file, but nor does the stdout case; exiting the program takes care of that for us).

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

This one worked for me:

>> print(df)
                          TotalVolume  Symbol
2016-04-15 09:00:00       108400       2802.T
2016-04-15 09:05:00       50300        2802.T

>> print(df.set_index(pd.to_datetime(df.index.values) - datetime(2016, 4, 15)))

             TotalVolume  Symbol
09:00:00     108400       2802.T
09:05:00     50300        2802.T

Jenkins restrict view of jobs per user

I use combination of several plugins - for the basic assignment of roles and permission I use Role Strategy Plugin.

When I need to split some role depending on parameters (e.g. everybody with job-runner is able to run jobs, but user only user UUU is allowed to run the deployment job to deploy on machine MMM), I use Python Plugin and define a python script as first build step and end with sys.exit(-1) when the job is forbidden to be run with the given combination of parameters.

Build User Vars Plugin provides me the information about the user executing the job as environment variables.

E.g:

import os
import sys

print os.environ["BUILD_USER"], "deploying to", os.environ["target_host"]

# only some users are allowed to deploy to servers "MMM"
mmm_users = ["UUU"]

if os.environ["target_host"] != "MMM" or os.environ["BUILD_USER"] in mmm_users:
    print "access granted"
else:
    print "access denied"
    sys.exit(-1)

How can I avoid ResultSet is closed exception in Java?

I got same error everything was correct only i was using same statement interface object to execute and update the database. After separating i.e. using different objects of statement interface for updating and executing query i resolved this error. i.e. do get rid from this do not use same statement object for both updating and executing the query.

Disable developer mode extensions pop up in Chrome

Now, we need to handle it using following -

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("chrome.switches", "--disable-extensions --disable-extensions-file-access-check --disable-extensions-http-throttling");

Apart from --disable-extensions, we also need to add --disable-extensions-file-access-check (and/or) --disable-extensions-http-throttling chrome switches.

Load local HTML file in a C# WebBrowser

Update on @ghostJago answer above

for me it worked as the following lines in VS2017

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));

Play sound file in a web-page in the background

<audio controls autoplay loop>
  <source src="path/your_song.mp3" type="audio/ogg">
  <embed src="path/your_song.mp3" autostart="true" loop="true" hidden="true"> 
</audio>

[ps. replace the "path/your_song.mp3" with the folder and the song title eg. "music/samplemusic.mp3" or "media/bgmusic.mp3" etc.

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

Accessing elements by type in javascript

var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
    var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
    for (;i<l;i++) {
        if (elems[i].type.toLowerCase() === "text") {
            ret.push(elems[i]);
        }
    }

    return ret;
}());

How to increase an array's length

Example of Array length change method (with old data coping):

static int[] arrayLengthChange(int[] arr, int newLength) {
    int[] arrNew = new int[newLength];
    System.arraycopy(arr, 0, arrNew, 0, arr.length);
    return arrNew;
}

Negative weights using Dijkstra's Algorithm

you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.

this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]

in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.

Angular 2 Date Input not binding to date value

use DatePipe

> // ts file

import { DatePipe } from '@angular/common';

@Component({
....
providers:[DatePipe]
})

export class FormComponent {

constructor(private datePipe : DatePipe){}

    demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);  
}

JavaScript/regex: Remove text between parentheses

If you need to remove text inside nested parentheses, too, then:

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);

Change background color for selected ListBox item

I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.

<Style.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>

When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey instead of ControlBrushKey:

<Style.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>

Hope this helps someone out.

Converting string to byte array in C#

This has been answered quite a lot, but for me, the only working method is this one:

    public static byte[] StringToByteArray(string str)
    {
        byte[] array = Convert.FromBase64String(str);
        return array;
    }

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

JavaScript single line 'if' statement - best syntax, this alternative?

**Old Method:**
if(x){
   add(x);
}
New Method:
x && add(x);

Even assign operation also we can do with round brackets

exp.includes('regexp_replace') && (exp = exp.replace(/,/g, '@&'));

Append same text to every cell in a column in Excel

It's a simple "&" function.

=cell&"yourtexthere"

Example - your cell says Mickey, and you want Mickey Mouse. Mickey is in A2. In B2, type

=A2&" Mouse"

Then, copy and "paste special" for values.

B2 now reads "Mickey Mouse"

'dict' object has no attribute 'has_key'

has_key was removed in Python 3. From the documentation:

  • Removed dict.has_key() – use the in operator instead.

Here's an example:

if start not in graph:
    return None

Controlling Maven final name of jar artifact

The approach you've been using indeed does jar file with a string 'testing' in its name, as you specified, but the default install command sends it to your ~/.m2/repository directory, as seen in this output line:

/tmp/mvn_test/my-app/target/my-app-testing.jar to /home/maxim/.m2/repository/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.jar

It seems to me that you're trying to generate a jar with such name and then copy it to a directory of your choice.

Try using outputDirectory property as described here: http://maven.apache.org/plugins/maven-jar-plugin/jar-mojo.html

Arrays.asList() of an array

this is from Java API "sort

public static void sort(List list) Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list)."

it has to do with implementing the Comparable interface

How to close activity and go back to previous activity in android

on onCreate method of your activity write the following code.

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

Then override the onOptionsItem selected method of your activity as follows

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case android.R.id.home:
            finish();
    }
    return super.onOptionsItemSelected(item);
}

And you are good to go.

Giving UIView rounded corners

You can use following custom UIView class which can also change border color and width. As this is IBDesignalbe You can change the attributes in interface builder as well.

enter image description here

import UIKit

@IBDesignable public class RoundedView: UIView {

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 2.0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }

}

How to get just one file from another branch

git checkout branch_name file_name

Example:

git checkout master App.java

This will not work if your branch name has a period in it.

git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.

Returning a boolean from a Bash function

myfun(){
    [ -d "$1" ]
}
if myfun "path"; then
    echo yes
fi
# or
myfun "path" && echo yes

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

Try this!

Build phases > Add > New Run Script Phase

Code:

# Type a script or drag a script file from your workspace to insert its path.
# skip if we run in debug
if [ "$CONFIGURATION" == "Debug" ]; then
echo "Skip frameworks cleaning in debug version"
exit 0
fi

APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"

# This script loops through the frameworks embedded in the application and
# removes unused architectures.
find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK
do
FRAMEWORK_EXECUTABLE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable)
FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME"
echo "Executable is $FRAMEWORK_EXECUTABLE_PATH"

EXTRACTED_ARCHS=()

for ARCH in $ARCHS
do
echo "Extracting $ARCH from $FRAMEWORK_EXECUTABLE_NAME"
lipo -extract "$ARCH" "$FRAMEWORK_EXECUTABLE_PATH" -o "$FRAMEWORK_EXECUTABLE_PATH-$ARCH"
EXTRACTED_ARCHS+=("$FRAMEWORK_EXECUTABLE_PATH-$ARCH")
done

echo "Merging extracted architectures: ${ARCHS}"
lipo -o "$FRAMEWORK_EXECUTABLE_PATH-merged" -create "${EXTRACTED_ARCHS[@]}"
rm "${EXTRACTED_ARCHS[@]}"

echo "Replacing original executable with thinned version"
rm "$FRAMEWORK_EXECUTABLE_PATH"
mv "$FRAMEWORK_EXECUTABLE_PATH-merged" "$FRAMEWORK_EXECUTABLE_PATH"

done

Xcode will refuse to sign them. The above script removes unused architectures.

Split varchar into separate columns in Oracle

Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
       SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
  FROM YOUR_TABLE t

Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

Reference:

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How to get UTC+0 date in Java 8?

In java8, I would use the Instant class which is already in UTC and is convenient to work with.

import java.time.Instant;

Instant ins = Instant.now();
long ts = ins.toEpochMilli();

Instant ins2 = Instant.ofEpochMilli(ts)

Alternatively, you can use the following:

import java.time.*;

Instant ins = Instant.now(); 

OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));

Back to Instant

Instant ins4 = Instant.from(odt);

The application may be doing too much work on its main thread

Optimize your images ... Dont use images larger than 100KB ... Image loading takes too much CPU and cause your app hangs .

How to create a file with a given size in Linux?

Use this command:

dd if=$INPUT-FILE of=$OUTPUT-FILE bs=$BLOCK-SIZE count=$NUM-BLOCKS

To create a big (empty) file, set $INPUT-FILE=/dev/zero.
Total size of the file will be $BLOCK-SIZE * $NUM-BLOCKS.
New file created will be $OUTPUT-FILE.

Angular ngClass and click event for toggling class

If you want to toggle text with a toggle button.

HTMLfile which is using bootstrap:

<input class="btn" (click)="muteStream()"  type="button"
          [ngClass]="status ? 'btn-success' : 'btn-danger'" 
          [value]="status ? 'unmute' : 'mute'"/>

TS file:

muteStream() {
   this.status = !this.status;
}

Should operator<< be implemented as a friend or as a member function?

friend operator = equal rights as class

friend std::ostream& operator<<(std::ostream& os, const Object& object) {
    os << object._atribute1 << " " << object._atribute2 << " " << atribute._atribute3 << std::endl;
    return os;
}

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

"Too many characters in character literal error"

A char can hold a single character only, a character literal is a single character in single quote, i.e. '&' - if you have more characters than one you want to use a string, for that you have to use double quotes:

case "&&": 

Passing parameter using onclick or a click binding with KnockoutJS

If you set up a click binding in Knockout the event is passed as the second parameter. You can use the event to obtain the element that the click occurred on and perform whatever action you want.

Here is a fiddle that demonstrates: http://jsfiddle.net/jearles/xSKyR/

Alternatively, you could create your own custom binding, which will receive the element it is bound to as the first parameter. On init you could attach your own click event handler to do any actions you wish.

http://knockoutjs.com/documentation/custom-bindings.html

HTML

<div>
    <button data-bind="click: clickMe">Click Me!</button>
</div>

Js

var ViewModel = function() {
    var self = this;
    self.clickMe = function(data,event) {

      var target = event.target || event.srcElement;

      if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;

      target.parentNode.innerHTML = "something";
    }
}

ko.applyBindings(new ViewModel());

Python MySQLdb TypeError: not all arguments converted during string formatting

I encountered this error while executing SELECT * FROM table; I traced the error to cursor.py line 195.

if args is not None:
        if isinstance(args, dict):
            nargs = {}
            for key, item in args.items():
                if isinstance(key, unicode):
                    key = key.encode(db.encoding)
                nargs[key] = db.literal(item)
            args = nargs
        else:
            args = tuple(map(db.literal, args))
        try:
            query = query % args
        except TypeError as m:
            raise ProgrammingError(str(m))

Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.

How to increase the Java stack size?

If you want to play with the thread stack size, you'll want to look at the -Xss option on the Hotspot JVM. It may be something different on non Hotspot VM's since the -X parameters to the JVM are distribution specific, IIRC.

On Hotspot, this looks like java -Xss16M if you want to make the size 16 megs.

Type java -X -help if you want to see all of the distribution specific JVM parameters you can pass in. I am not sure if this works the same on other JVMs, but it prints all of Hotspot specific parameters.

For what it's worth - I would recommend limiting your use of recursive methods in Java. It's not too great at optimizing them - for one the JVM doesn't support tail recursion (see Does the JVM prevent tail call optimizations?). Try refactoring your factorial code above to use a while loop instead of recursive method calls.

PHP: maximum execution time when importing .SQL data file

you must change php_admin_value max_execution_time in your Alias config (\XAMPP\alias\phpmyadmin.conf)

answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded

Is there a goto statement in Java?

Of course it is keyword, but it is not used on level of source code.

But if you use jasmin or other lower level language, which is transformed to bytecode, then "goto" is there

m2e error in MavenArchiver.getManifest()

I had also faced the same issue and it got resolved by commenting the version element in POM.xml as show.

org.apache.maven.archiver.[MavenArchiver](https://maven.apache.org/shared/maven-archiver/apidocs/org/apache/maven/archiver/MavenArchiver.html).getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)

<plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <!-- <version>3.5.1</version> -->
    <configuration>
      <source>1.7</source>
      <target>1.7</target>
    </configuration>
  </plugin>
  <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <!-- <version>3.1.0</version> -->
    <configuration>
      <warSourceDirectory>WebContent</warSourceDirectory>
      <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
  </plugin>
</plugins>

What's the easiest way to call a function every 5 seconds in jQuery?

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>

Hive: Convert String to Integer

It would return NULL but if taken as BIGINT would show the number

Correct way to populate an Array with a Range in Ruby

Sounds like you're doing this:

0..10.to_a

The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:

(0..10).to_a

List of encodings that Node.js supports

If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:

npm install iconv

npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz

> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild

gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.

fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.

Unable to convert MySQL date/time value to System.DateTime

You must add Convert Zero Datetime=True to your connection string, for example:

server=localhost;User Id=root;password=mautauaja;Persist Security Info=True;database=test;Convert Zero Datetime=True

return query based on date

if you want to get items anywhere on that date you need to compare two dates

You can create two dates off of the first one like this, to get the start of the day, and the end of the day.

var startDate = new Date(); // this is the starting date that looks like ISODate("2014-10-03T04:00:00.188Z")

startDate.setSeconds(0);
startDate.setHours(0);
startDate.setMinutes(0);

var dateMidnight = new Date(startDate);
dateMidnight.setHours(23);
dateMidnight.setMinutes(59);
dateMidnight.setSeconds(59);

### MONGO QUERY

var query = {
        inserted_at: {
                    $gt:morning,
                    $lt:dateScrapedMidnight
        }
};

//MORNING: Sun Oct 12 2014 00:00:00 GMT-0400 (EDT)
//MIDNIGHT: Sun Oct 12 2014 23:59:59 GMT-0400 (EDT)

What is the difference between "screen" and "only screen" in media queries?

Let's break down your examples one by one.

@media (max-width:632px)

This one is saying for a window with a max-width of 632px that you want to apply these styles. At that size you would be talking about anything smaller than a desktop screen in most cases.

@media screen and (max-width:632px)

This one is saying for a device with a screen and a window with max-width of 632px apply the style. This is almost identical to the above except you are specifying screen as opposed to the other available media types the most common other one being print.

@media only screen and (max-width:632px)

Here is a quote straight from W3C to explain this one.

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

As there is no such media type as "only", the style sheet should be ignored by older browsers.

Here's the link to that quote that is shown in example 9 on that page.

Hopefully this sheds some light on media queries.

EDIT:

Be sure to check out @hybrids excellent answer on how the only keyword is really handled.

Python convert tuple to string

Use str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

How to locate the git config file in Mac

The global Git configuration file is stored at $HOME/.gitconfig on all platforms.

However, you can simply open a terminal and execute git config, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig, unless you particularly want to.

How to import multiple csv files in a single load?

Note that you can use other tricks like :

-- One or more wildcard:
       .../Downloads20*/*.csv
--  braces and brackets   
       .../Downloads201[1-5]/book.csv
       .../Downloads201{11,15,19,99}/book.csv

What is pipe() function in Angular

The Pipes you are talking about in the starting description are different from the pipe you showed in the example.

In Angular(2|4|5) Pipes are used to format view as you said. I think you have a basic understanding of pipes in Angular, you can learn more about that from this link - Angular Pipe Doc

The pipe() you have shown in the example is the pipe() method of RxJS 5.5 (RxJS is the default for all Angular apps). In Angular5 all the RxJS operators can be imported using single import and they are now combined using the pipe method.

tap() - RxJS tap operator will look at the Observable value and do something with that value. In other words, after a successful API request, the tap() operator will do any function you want it to perform with the response. In the example, it will just log that string.

catchError() - catchError does exactly the same thing but with error response. If you want to throw an error or want to call some function if you get an error, you can do it here. In the example, it will call handleError() and inside that, it will just log that string.

Print array to a file

Below Should work nice and more readable using <pre>

<?php 

ob_start();
echo '<pre>';
print_r($array);
$outputBuffer = ob_get_contents();
ob_end_flush();
file_put_contents('your file name', $outputBuffer);
?>

De-obfuscate Javascript code to make it readable again

Try this: http://jsbeautifier.org/

I tested with your code and worked as good as possible. =D

How to import a new font into a project - Angular 5

You can try creating a css for your font with font-face (like explained here)

Step #1

Create a css file with font face and place it somewhere, like in assets/fonts

customfont.css

@font-face {
    font-family: YourFontFamily;
    src: url("/assets/font/yourFont.otf") format("truetype");
}

Step #2

Add the css to your .angular-cli.json in the styles config

"styles":[
 //...your other styles
 "assets/fonts/customFonts.css"
 ]

Do not forget to restart ng serve after doing this

Step #3

Use the font in your code

component.css

span {font-family: YourFontFamily; }

Set the table column width constant regardless of the amount of text in its cells?

See: http://www.html5-tutorials.org/tables/changing-column-width/

After the table tag, use the col element. you don't need a closing tag.

For example, if you had three columns:

<table>
  <colgroup>
    <col style="width:40%">
    <col style="width:30%">
    <col style="width:30%">
  </colgroup>  
  <tbody>
    ...
  </tbody>
</table>

Write values in app.config file

As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings. But: Using Settings[key] = value will not work if the key doesn't exist.
Using Settings.Add(key, value), if the key already exists, it will join the new value to its value(s) separated by a comma, something like <add key="myKey" value="value1, value2, value3" />

To avoid these unexpected results, you have to handle two scenario's

  • If entry with the given key exists? then update its value
  • if entry with the given key doesn't exist? then create new entry(key,value)

Code

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

For more info about the check entry == null, check this post.
Hope this will help someone.

VueJS conditionally add an attribute for an element

<input :required="condition">

You don't need <input :required="test ? true : false"> because if test is truthy you'll already get the required attribute, and if test is falsy you won't get the attribute. The true : false part is redundant, much like this...

if (condition) {
    return true;
} else {
    return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed

The simplest way of doing this binding, then, is <input :required="condition">

Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of !! does the trick.
  <input :required="!!condition">

How to display 3 buttons on the same line in css

You need to float all the buttons to left and make sure its width to fit within outer container.

CSS:

.btn{

   float:left;
}

HTML:

    <button type="submit" class="btn" onClick="return false;" >Save</button>
    <button type="submit" class="btn" onClick="return false;">Publish</button>
    <button class="btn">Back</button>

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

How to use jQuery to select a dropdown option?

if your options have a value, you can do this:

$('select').val("the-value-of-the-option-you-want-to-select");

'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

How to show form input fields based on select value?

Demo on JSFiddle

$(document).ready(function () {
    toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
    // this will call our toggleFields function every time the selection value of our other field changes
    $("#dbType").change(function () {
        toggleFields();
    });

});
// this toggles the visibility of other server
function toggleFields() {
    if ($("#dbType").val() === "other")
        $("#otherServer").show();
    else
        $("#otherServer").hide();
}

HTML:

    <p>Choose type</p>
    <p>Server:
        <select id="dbType" name="dbType">
          <option>Choose Database Type</option>
          <option value="oracle">Oracle</option>
          <option value="mssql">MS SQL</option>
          <option value="mysql">MySQL</option>
          <option value="other">Other</option>
        </select>
    </p>
    <div id="otherServer">
        <p>Server:
            <input type="text" name="server_name" />
        </p>
        <p>Port:
            <input type="text" name="port_no" />
        </p>
    </div>
    <p align="center">
        <input type="submit" value="Submit!" />
    </p>

How can I select all children of an element except the last child?

You can use the negation pseudo-class :not() against the :last-child pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:

:not(:last-child) { /* styles */ }

How to have stored properties in Swift, the same way I had on Objective-C?

Associated objects API is a bit cumbersome to use. You can remove most of the boilerplate with a helper class.

public final class ObjectAssociation<T: AnyObject> {

    private let policy: objc_AssociationPolicy

    /// - Parameter policy: An association policy that will be used when linking objects.
    public init(policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {

        self.policy = policy
    }

    /// Accesses associated object.
    /// - Parameter index: An object whose associated object is to be accessed.
    public subscript(index: AnyObject) -> T? {

        get { return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? }
        set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, policy) }
    }
}

Provided that you can "add" a property to objective-c class in a more readable manner:

extension SomeType {

    private static let association = ObjectAssociation<NSObject>()

    var simulatedProperty: NSObject? {

        get { return SomeType.association[self] }
        set { SomeType.association[self] = newValue }
    }
}

As for the solution:

extension CALayer {

    private static let initialPathAssociation = ObjectAssociation<CGPath>()
    private static let shapeLayerAssociation = ObjectAssociation<CAShapeLayer>()

    var initialPath: CGPath! {
        get { return CALayer.initialPathAssociation[self] }
        set { CALayer.initialPathAssociation[self] = newValue }
    }

    var shapeLayer: CAShapeLayer? {
        get { return CALayer.shapeLayerAssociation[self] }
        set { CALayer.shapeLayerAssociation[self] = newValue }
    }
}

arranging div one below the other

If you want the two divs to be displayed one above the other, the simplest answer is to remove the float: left;from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.

Alternatively, you could simply add clear:both; to the divs, which will force the floated content to clear previous floats.

How can I set a dynamic model name in AngularJS?

Or you can use

<select [(ngModel)]="Answers[''+question.Name+'']" ng-options="option for option in question.Options">
        </select>

Automatically start a Windows Service on install

You can use the following command line to start the service:

net start *servicename*

Linux delete file with size 0

On Linux, the stat(1) command is useful when you don't need find(1):

(( $(stat -c %s "$filename") )) || rm "$filename"

The stat command here allows us just to get the file size, that's the -c %s (see the man pages for other formats). I am running the stat program and capturing its output, that's the $( ). This output is seen numerically, that's the outer (( )). If zero is given for the size, that is FALSE, so the second part of the OR is executed. Non-zero (non-empty file) will be TRUE, so the rm will not be executed.

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

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

file -ib "$file"

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

Setting the zoom level for a MKMapView

Based on @AdilSoomro's great answer. I have come up with this:

@interface MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated;

-(double) getZoomLevel;
@end



@implementation MKMapView (ZoomLevel)

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
    MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
    [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}


-(double) getZoomLevel {
    return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta));
}

@end

hash keys / values as array

Don't know if it helps, but the "foreach" goes through all the keys: for (var key in obj1) {...}

Convert string to datetime in vb.net

You can try with ParseExact method

Sample

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

List of special characters for SQL LIKE clause

Potential answer for SQL Server

Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.

Records .Where(r => r.Name.Contains("lkjwer--_~[]"))

-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'

So I haven't tested it yet but it looks like potentially the ESCAPE '~' keyword may allow for automatic escaping of a string for use within a like expression.

Can I have an onclick effect in CSS?

Answer as of 2020:

The best way (actually the only way*) to simulate an actual click event using only CSS (rather than just hovering on an element or making an element active, where you don't have mouseUp) is to use the checkbox hack. It works by attaching a label to an <input type="checkbox"> element via the label's for="" attribute.

This feature has broad browser support (the :checked pseudo-class is IE9+).

Apply the same value to an <input>'s ID attribute and an accompanying <label>'s for="" attribute, and you can tell the browser to re-style the label on click with the :checked pseudo-class, thanks to the fact that clicking a label will check and uncheck the "associated" <input type="checkbox">.

* You can simulate a "selected" event via the :active or :focus pseudo-class in IE7+ (e.g. for a button that's normally 50px wide, you can change its width while active: #btnControl:active { width: 75px; }), but those are not true "click" events. They are "live" the entire time the element is selected (such as by Tabbing with your keyboard), which is a little different from a true click event, which fires an action on - typically - mouseUp.


Basic demo of the checkbox hack (the basic code structure for what you're asking):

_x000D_
_x000D_
label {
    display: block;
    background: lightgrey;
    width: 100px;
    height: 100px;
}

#demo:checked + label {
    background: blue;
    color: white;
}
_x000D_
<input type="checkbox" id="demo"/>
<label for="demo">I'm a square. Click me.</label>
_x000D_
_x000D_
_x000D_

Here I've positioned the label right after the input in my markup. This is so that I can use the adjacent sibling selector (the + key) to select only the label that immediately follows my #demo checkbox. Since the :checked pseudo-class applies to the checkbox, #demo:checked + label will only apply when the checkbox is checked.

Demo for re-sizing an image on click, which is what you're asking:

_x000D_
_x000D_
#btnControl {
    display: none;
}

#btnControl:checked + label > img {
    width: 70px;
    height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl"><img src="https://placekitten.com/200/140" id="btnLeft" /></label>
_x000D_
_x000D_
_x000D_

With that being said, there is some bad news. Because a label can only be associated with one form control at a time, that means you can't just drop a button inside the <label></label> tags and call it a day. However, we can use some CSS to make the label look and behave fairly close to how an HTML button looks and behaves.

Demo for imitating a button click effect, above and beyond what you're asking:

_x000D_
_x000D_
#btnControl {
    display: none;
}

.btn {
    width: 60px;
    height: 20px;
    background: silver;
    border-radius: 5px;
    padding: 1px 3px;
    box-shadow: 1px 1px 1px #000;
    display: block;
    text-align: center;
    background-image: linear-gradient(to bottom, #f4f5f5, #dfdddd);
    font-family: arial;
    font-size: 12px;
    line-height:20px;
}

.btn:hover {
    background-image: linear-gradient(to bottom, #c3e3fa, #a5defb);
}


.btn:active {
    margin-left: 1px 1px 0;
    box-shadow: -1px -1px 1px #000;
    outline: 1px solid black;
    -moz-outline-radius: 5px;
    background-image: linear-gradient(to top, #f4f5f5, #dfdddd);
}

#btnControl:checked + label {
    width: 70px;
    height: 74px;
    line-height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
_x000D_
_x000D_

Most of the CSS in this demo is just for styling the label element. If you don't actually need a button, and any old element will suffice, then you can remove almost all of the styles in this demo, similar to my second demo above.

You'll also notice I have one prefixed property in there, -moz-outline-radius. A while back, Mozilla added this awesome non-spec property to Firefox, but the folks at WebKit decided they aren't going to add it, unfortunately. So consider that line of CSS just a progressive enhancement for people who use Firefox.

HTML anchor tag with Javascript onclick event

Use following code to show menu instead go to href addres

_x000D_
_x000D_
function show_more_menu(e) {_x000D_
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
_x000D_
_x000D_

How do I run a PowerShell script when the computer starts?

Be sure, whenever you want PowerShell to run automatically / in the background / non-interactive, it’s a good idea to specify the parameters -ExecutionPolicy Bypass to PowerShell.exe

PowerShell.exe -ExecutionPolicy Bypass

Can I add an image to an ASP.NET button?

.my_btn{ 
  font-family:Arial; 
  font-size:10pt; 
  font-weight:normal; 
  height:30px; 
  line-height:30px; 
  width:98px; 
  border:0px;
  background-image:url('../Images/menu_image.png'); 
  cursor:pointer;
}

<asp:Button ID="clickme" runat="server" Text="Click" CssClass="my_btn" />

NodeJS accessing file with relative path

Simple! The folder named .. is the parent folder, so you can make the path to the file you need as such

var foobar = require('../config/dev/foobar.json');

If you needed to go up two levels, you would write ../../ etc

Some more details about this in this SO answer and it's comments

R Apply() function on specific dataframe columns

I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.

String.Format not work in TypeScript

String Interpolation

Note: As of TypeScript 1.4, string interpolation is available in TypeScript:

var a = "Hello";
var b = "World";

var text = `${a} ${b}`

This will compile to:

var a = "Hello";
var b = "World";
var text = a + " " + b;

String Format

The JavaScript String object doesn't have a format function. TypeScript doesn't add to the native objects, so it also doesn't have a String.format function.

For TypeScript, you need to extend the String interface and then you need to supply an implementation:

interface String {
    format(...replacements: string[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

You can then use the feature:

var myStr = 'This is an {0} for {0} purposes: {1}';

alert(myStr.format('example', 'end'));

You could also consider string interpolation (a feature of Template Strings), which is an ECMAScript 6 feature - although to use it for the String.format use case, you would still need to wrap it in a function in order to supply a raw string containing the format and then positional arguments. It is more typically used inline with the variables that are being interpolated, so you'd need to map using arguments to make it work for this use case.

For example, format strings are normally defined to be used later... which doesn't work:

// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';

// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;

So to use string interpolation, rather than a format string, you would need to use:

function myTemplate(a: string, b: string) {
    var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
}

alert(myTemplate('example', 'end'));

The other common use case for format strings is that they are used as a resource that is shared. I haven't yet discovered a way to load a template string from a data source without using eval.

SQL Server : error converting data type varchar to numeric

If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:

Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.

Or TRY_CONVERT/TRY_CAST:

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

C++ passing an array pointer as a function argument

You're over-complicating it - it just needs to be:

void generateArray(int *a, int si)
{
    for (int j = 0; j < si; j++)
        a[j] = rand() % 9;
}

int main()
{
    const int size=5;
    int a[size];

    generateArray(a, size);

    return 0;
}

When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.

Better way to generate array of all letters in the alphabet

Define any languages an enum, and call getAlphabet();

char[] armenianAlphabet = getAlphabet(LocaleLanguage.ARMENIAN);
char[] russianAlphabet = getAlphabet(LocaleLanguage.RUSSIAN);

// get uppercase alphabet 
char[] currentAlphabet = getAlphabet(true);
    
System.out.println(armenianAlphabet);
System.out.println(russianAlphabet);
System.out.println(currentAlphabet);

result

I/System.out: ??????????????????????????????????????

I/System.out: ????????????????????????????????

I/System.out: ABCDEFGHIJKLMNOPQRSTUVWXYZ

private char[] getAlphabet(){
    return getAlphabet(false);
}

private char[] getAlphabet(boolean flagToUpperCase){
    Locale locale = getResources().getConfiguration().locale;
    LocaleLanguage language = LocaleLanguage.getLocalLanguage(locale);
    return getAlphabet(language, flagToUpperCase);
}

private char[] getAlphabet(LocaleLanguage localeLanguage, boolean flagToUpperCase){
    if (localeLanguage == null)
        localeLanguage = LocaleLanguage.ENGLISH;

    char firstLetter = localeLanguage.getFirstLetter();
    char lastLetter = localeLanguage.getLastLetter();
    int alphabetSize = lastLetter - firstLetter + 1;

    char[] alphabet = new char[alphabetSize];

    for (int index = 0; index < alphabetSize; index++ ){
        alphabet[index] = (char) (index + firstLetter);
    }

    if (flagToUpperCase){
        alphabet = new String(alphabet).toUpperCase().toCharArray();
    }

    return alphabet;
}

private enum LocaleLanguage{
    ARMENIAN(new Locale("hy"), '?', '?'),
    RUSSIAN(new Locale("ru"), '?','?'),
    ENGLISH(new Locale("en"), 'a','z');

    private final Locale mLocale;
    private final char mFirstLetter;
    private final char mLastLetter;

    LocaleLanguage(Locale locale, char firstLetter, char lastLetter) {
        this.mLocale = locale;
        this.mFirstLetter = firstLetter;
        this.mLastLetter = lastLetter;
    }

    public Locale getLocale() {
        return mLocale;
    }

    public char getFirstLetter() {
        return mFirstLetter;
    }

    public char getLastLetter() {
        return mLastLetter;
    }

    public String getDisplayLanguage(){
        return getLocale().getDisplayLanguage();
    }

    public String getDisplayLanguage(LocaleLanguage locale){
        return getLocale().getDisplayLanguage(locale.getLocale());
    }

    @Nullable
    public static LocaleLanguage getLocalLanguage(Locale locale){
        if (locale == null)
            return LocaleLanguage.ENGLISH;

        for (LocaleLanguage localeLanguage : LocaleLanguage.values()){
            if (localeLanguage.getLocale().getLanguage().equals(locale.getLanguage()))
                return localeLanguage;
        }

        return null;
    }
}

Should black box or white box testing be the emphasis for testers?

White Box Testing equals Software Unit Test. The developer or a development level tester (e.g. another developer) ensures that the code he has written is working properly according to the detailed level requirements before integrating it in the system.

Black Box Testing equals Integration Testing. The tester ensures that the system works according to the requirements on a functional level.

Both test approaches are equally important in my opinion.

A thorough unit test will catch defects in the development stage and not after the software has been integrated into the system. A system level black box test will ensure all software modules behave correctly when integrated together. A unit test in the development stage would not catch these defects since modules are usually developed independent from each other.

How to import a SQL Server .bak file into MySQL?

For those attempting Richard's solution above, here are some additional information that might help navigate common errors:

1) When running restore filelistonly you may get Operating system error 5(Access is denied). If that's the case, open SQL Server Configuration Manager and change the login for SQLEXPRESS to a user that has local write privileges.

2) @"This will list the contents of the backup - what you need is the first fields that tell you the logical names" - if your file lists more than two headers you will need to also account for what to do with those files in the RESTORE DATABASE command. If you don't indicate what to do with files beyond the database and the log, the system will apparently try to use the attributes listed in the .bak file. Restoring a file from someone else's environment will produce a 'The path has invalid attributes. It needs to be a directory' (as the path in question doesn't exist on your machine). Simply providing a MOVE statement resolves this problem.

In my case there was a third FTData type file. The MOVE command I added:

MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf',
MOVE 'sysft_...' TO 'c:\temp\other';

in my case I actually had to make a new directory for the third file. Initially I tried to send it to the same folder as the .mdf file but that produced a 'failed to initialize correctly' error on the third FTData file when I executed the restore.

SQL statement to select all rows from previous day

In SQL Server do like this:

where cast(columnName as date) = cast(getdate() -1 as date)

You should cast both sides of the expression to date to avoid issues with time formatting.

If you need to control interval in more detail, then you should try something like:

declare @start datetime = cast(getdate() - 1 as date)
declare @end datetime = cast(getdate() - 1 as date)
set @end = dateadd(second, 86399, @end)

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

New -> Batch Drawable Import -> Click on Add button -> Select image -> Select Target Resolution, Target Name, Format -> Ok

Reloading a ViewController

If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:

[self viewDidLoad];

again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order. like.

[self viewDidLoad]; [self viewWillAppear:YES];

I think there should be a more specific solution like refresh button in browser.

What are named pipes?

Named pipes is a windows system for inter-process communication. In the case of SQL server, if the server is on the same machine as the client, then it is possible to use named pipes to tranfer the data, as opposed to TCP/IP.

rails simple_form - hidden field - create?

= f.input_field :title, as: :hidden, value: "some value"

Is also an option. Note, however, that it skips any wrapper defined for your form builder.

How do I convert a String to an int in Java?

You can use new Scanner("1244").nextInt(). Or ask if even an int exists: new Scanner("1244").hasNextInt()

Accessing MVC's model property from Javascript

If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:

$(document).ready(function () {

    @{  var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         var json = serializer.Serialize(Model);
    }

    var model = @Html.Raw(json);
    if(model != null && @Html.Raw(json) != "undefined")
    {
        var id= model.Id;
        var mainFloorPlanId = model.MainFloorPlanId ;
        var imageDirectory = model.ImageDirectory ;
        var iconsDirectory = model.IconsDirectory ;
    }
});

Hope this helps...

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

C++ Double Address Operator? (&&)

I believe that is is a move operator. operator= is the assignment operator, say vector x = vector y. The clear() function call sounds like as if it is deleting the contents of the vector to prevent a memory leak. The operator returns a pointer to the new vector.

This way,

std::vector<int> a(100, 10);
std::vector<int> b = a;
for(unsigned int i = 0; i < b.size(); i++)
{
    std::cout << b[i] << ' ';
}

Even though we gave vector a values, vector b has the values. It's the magic of the operator=()!

MSDN -- How to create a move constructor

Git diff says subproject is dirty

git submodule foreach --recursive git checkout .

This didn't do the trick for me but it gave me a list of files (in my case only one) that had been changed in the submodule (without me doing anything there).

So I could head over to the submodule and git status showed me that my HEAD was detached -> git checkout master, git status to see the modified file once again, git checkout >filename<, git pull and everything fine again.

Create a day-of-week column in a Pandas dataframe using Python

Just in case if .dt doesn't work for you. Trying .DatetimeIndex might help. Hope the code and our test result here help you fix it. Regards,

import pandas as pd
import datetime

df = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03'],'Number':[1,2,3]})

df['Day'] = pd.DatetimeIndex(df['Date']).day_name() # week day name
df.head()

enter image description here

Angular cli generate a service and include the provider in one step

slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0

ng g service backendApi --module=app.module

Must issue a STARTTLS command first

I also faced the same issue while I was building email notification application. you just need to add one line. Below one saved my day.

props.put("mail.smtp.starttls.enable", "true");

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. h13-v6sm10627790pgp.13 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.smruti.email.EmailProject.EmailSend.main(EmailSend.java:99)

Hope this helps you.

Connect Device to Mac localhost Server?

Always use the IP that is shown in your Network settings. It changes when you change location and you use another wireless connection.

For example in my case now it is: 10.0.0.5

Service located in another namespace

You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Actually my problem was that the command line mvn utility wouldn't see the changes for some reason. I turned on the Auto-deploy in the Deployment Scanner and there was still no difference. HOWEVER... I was twiddling around with the Eclipse environment and because I had added a JBoss server for it's Servers window I discovered I had the ability to "Add or Remove..." modules in my workspace. Once the project was added whenever I made a change to code the code change was detected by the Deployment Scanner and JBoss went thru the cycle of updating code!!! Works like a charm.

Here are the steps necessary to set this up;

First if you haven't done so add your JBoss Server to your Eclipse using File->New->Other->Server then go thru the motions of adding your JBoss AS 7 server. Being sure to locate the directory that you are using.

Once added, look down near the bottom of Eclipse to the "Servers" tab. You should see your JBoss server. Highlight it and look for "Add or Remove...". From there you should see your project.

Once added, make a small change to your code and watch JBoss go to town hot deploying for you.

Extracting hours from a DateTime (SQL Server 2005)

you must use datepart()

like 


datepart(hour , getdate())

Count occurrences of a char in a string using Bash

Building on everyone's great answers and comments, this is the shortest and sweetest version:

grep -o "$needle" <<< "$haystack" | wc -l

Adding Google Play services version to your app's manifest?

In Android Studio you can fix this by simply adding this to your Gradle file:

compile 'com.google.android.gms:play-services:6.5.87'

EDIT

Now, due to updates and new Gradle API the line you should use is:

implementation 'com.google.android.gms:play-services:12.0.0'

One more important tip: Avoid using bundled version of Google Play Services, but consider declaring just dependencies that your app needs to reduce it size as well as to reduce unnecessary hit to 65k methods limit. Something like (i.e. for Maps) this would be better than general play-services usage above:

implementation 'com.google.android.gms:play-services-maps:12.0.0'

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

various option are available such as:

 Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP);  // b = 123.12

BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP)  // b1= 123.12

 d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString());  // b2= 123.12



Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

Need table of key codes for android and presenter

You can find a complete list of Key Codes and an explanation here: http://code.google.com/p/androhid/wiki/Keycodes

Sometimes adding a WCF Service Reference generates an empty reference.cs

If you recently added a collection to your project when this started to occur, the problem may be caused by two collections which have the same CollectionDataContract attribute:

[CollectionDataContract(Name="AItems", ItemName="A")]
public class CollectionA : List<A> { }

[CollectionDataContract(Name="AItems", ItemName="A")]  // Wrong
public class CollectionB : List<B> { }

I fixed the error by sweeping through my project and ensuring that every Name and ItemName attribute was unique:

[CollectionDataContract(Name="AItems", ItemName="A")]
public class CollectionA : List<A> { }

[CollectionDataContract(Name="BItems", ItemName="B")]  // Corrected
public class CollectionB : List<B> { }

Then I refreshed the service reference and everything worked again.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How do I disable directory browsing?

Create an .htaccess file containing the following line:

Options -Indexes

That is one option. Another option is editing your apache configuration file.

In order to do so, you first need to open it with the command:

vim /etc/httpd/conf/httpd.conf

Then find the line: Options Indexes FollowSymLinks

Change that line to: Options FollowSymLinks

Lastly save and exit the file, and restart apache server with this command:

sudo service httpd restart

(You have a guide with screenshots here.)

Disable Proximity Sensor during call

Some more answers from the interwebs: "fix" the sensor (glue screen back on more, or clean it with alcohol, or blow it off with air sent through the headphone jack, tap on it, clean the screen, etc.).

Adjust (after some finding) setting in the "phone" app to disable proximity sensor use. No such setting in mine, that I could find. Proximity Screen Off Lite also didn't work, nor macrodroid.

Another option: root your phone and remove some files:

From root explorer or similar program delete these folders and file
/data/system/sensors
/data/misc/sensors
/persist/sensors/sns.reg

Or if you're truly desperate I suppose a totally different dialer system like TextNow or google hangouts dialer :|

Read XML Attribute using XmlDocument

XmlDocument.Attributes perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)

How to change the remote repository for a git submodule?

With Git 2.25 (Q1 2020), you can modify it.
See "Git submodule url changed" and the new command

git submodule set-url [--] <path> <newurl>

Original answer (May 2009, ten years ago)

Actually, a patch has been submitted in April 2009 to clarify gitmodule role.

So now the gitmodule documentation does not yet include:

The .gitmodules file, located in the top-level directory of a git working tree, is a text file with a syntax matching the requirements -of linkgit:git-config1.
[NEW]:
As this file is managed by Git, it tracks the +records of a project's submodules.
Information stored in this file is used as a hint to prime the authoritative version of the record stored in the project configuration file.
User specific record changes (e.g. to account for differences in submodule URLs due to networking situations) should be made to the configuration file, while record changes to be propagated (e.g. +due to a relocation of the submodule source) should be made to this file.

That pretty much confirm Jim's answer.


If you follow this git submodule tutorial, you see you need a "git submodule init" to add the submodule repository URLs to .git/config.

"git submodule sync" has been added in August 2008 precisely to make that task easier when URL changes (especially if the number of submodules is important).
The associate script with that command is straightforward enough:

module_list "$@" |
while read mode sha1 stage path
do
    name=$(module_name "$path")
    url=$(git config -f .gitmodules --get submodule."$name".url)
    if test -e "$path"/.git
    then
    (
        unset GIT_DIR
        cd "$path"
        remote=$(get_default_remote)
        say "Synchronizing submodule url for '$name'"
        git config remote."$remote".url "$url"
    )
    fi
done

The goal remains: git config remote."$remote".url "$url"

Using boolean values in C

This is what I use:

enum {false, true};
typedef _Bool bool;

_Bool is a built in type in C. It's intended for boolean values.

Throw keyword in function's signature

A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification

With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.

To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.

A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):

Exception-specification rationale

Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

T& operator*() const throw() { return *ptr; }

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

How to find all the dependencies of a table in sql server

In SQL Server 2008 or above I use the following query to find all the dependant stored procedures, user defined functions, triggers, etc. for a given table:

SELECT 
coalesce(Referenced_server_name+'.','')+ --possible server name if cross-server
coalesce(referenced_database_name+'.','')+ --possible database name if cross-database
coalesce(referenced_schema_name+'.','')+ --likely schema name
coalesce(referenced_entity_name,'') + --very likely entity name
coalesce('.'+col_name(referenced_ID,referenced_minor_id),'')AS [referencing],
coalesce(object_schema_name(Referencing_ID)+'.','')+ --likely schema name
object_name(Referencing_ID)+ --definite entity name
coalesce('.'+col_name(referencing_ID,referencing_minor_id),'') AS [referenced]
FROM sys.sql_expression_dependencies
WHERE referenced_id =object_id('Table_name')
ORDER BY [referenced]

Copy all the lines to clipboard

If you're using Vim in visual mode, the standard cut and paste keys also apply, at least with Windows.

  • CTRLA means "Mark the entire file.
  • CTRLC means "Copy the selection.
  • ESC means "De-select, so your next key press doesn't replace the entire file :-)

Under Ubuntu terminal (Gnome) at least, the standard copy also works (CTRLSHIFTC, although there doesn't appear to be a standard keyboard shortcut for select all (other than ALTE followed by A).

Javascript negative number

This is an old question but it has a lot of views so I think that is important to update it.

ECMAScript 6 brought the function Math.sign(), which returns the sign of a number (1 if it's positive, -1 if it's negative) or NaN if it is not a number. Reference

You could use it as:

var number = 1;

if(Math.sign(number) === 1){
    alert("I'm positive");
}else if(Math.sign(number) === -1){
    alert("I'm negative");
}else{
    alert("I'm not a number");
}

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

The SQL Server Maximums are disclosed http://msdn.microsoft.com/en-us/library/ms143432.aspx (this is the 2008 version)

A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.

Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)

At 100k items, it took some time then dropped with:

Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.

So 30k is possible, but just because you can do it - does not mean you should :)

Edit : Continued due to additional question.

50k worked, but 60k dropped out, so somewhere in there on my test rig btw.

In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)

Extracting text from HTML file using Python

I know there are a lot of answers already, but the most elegent and pythonic solution I have found is described, in part, here.

from bs4 import BeautifulSoup

text = ''.join(BeautifulSoup(some_html_string, "html.parser").findAll(text=True))

Update

Based on Fraser's comment, here is more elegant solution:

from bs4 import BeautifulSoup

clean_text = ''.join(BeautifulSoup(some_html_string, "html.parser").stripped_strings)

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

What's the fastest way to read a text file line-by-line?

You can't get any faster if you want to use an existing API to read the lines. But reading larger chunks and manually find each new line in the read buffer would probably be faster.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

Just search

open_basedir =

in php.ini and disable it. That's the simplest solution to solve this issue.

Before Changes open_basedir =

After Changes ;open_basedir =

P.s - After changes don't forget to restart your server.

Enjoy ;)

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Have you executed "setup_xampp.bat" script? It's inside XAMPP folder and it must be executed every time you change XAMPP folder.

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Resolve build errors due to circular dependency amongst classes

The way to think about this is to "think like a compiler".

Imagine you are writing a compiler. And you see code like this.

// file: A.h
class A {
  B _b;
};

// file: B.h
class B {
  A _a;
};

// file main.cc
#include "A.h"
#include "B.h"
int main(...) {
  A a;
}

When you are compiling the .cc file (remember that the .cc and not the .h is the unit of compilation), you need to allocate space for object A. So, well, how much space then? Enough to store B! What's the size of B then? Enough to store A! Oops.

Clearly a circular reference that you must break.

You can break it by allowing the compiler to instead reserve as much space as it knows about upfront - pointers and references, for example, will always be 32 or 64 bits (depending on the architecture) and so if you replaced (either one) by a pointer or reference, things would be great. Let's say we replace in A:

// file: A.h
class A {
  // both these are fine, so are various const versions of the same.
  B& _b_ref;
  B* _b_ptr;
};

Now things are better. Somewhat. main() still says:

// file: main.cc
#include "A.h"  // <-- Houston, we have a problem

#include, for all extents and purposes (if you take the preprocessor out) just copies the file into the .cc. So really, the .cc looks like:

// file: partially_pre_processed_main.cc
class A {
  B& _b_ref;
  B* _b_ptr;
};
#include "B.h"
int main (...) {
  A a;
}

You can see why the compiler can't deal with this - it has no idea what B is - it has never even seen the symbol before.

So let's tell the compiler about B. This is known as a forward declaration, and is discussed further in this answer.

// main.cc
class B;
#include "A.h"
#include "B.h"
int main (...) {
  A a;
}

This works. It is not great. But at this point you should have an understanding of the circular reference problem and what we did to "fix" it, albeit the fix is bad.

The reason this fix is bad is because the next person to #include "A.h" will have to declare B before they can use it and will get a terrible #include error. So let's move the declaration into A.h itself.

// file: A.h
class B;
class A {
  B* _b; // or any of the other variants.
};

And in B.h, at this point, you can just #include "A.h" directly.

// file: B.h
#include "A.h"
class B {
  // note that this is cool because the compiler knows by this time
  // how much space A will need.
  A _a; 
}

HTH.

json_decode returns NULL after webservice call

"?{"action":"set","user":"123123123123","status":"OK"}"

This little apostrophe in the beginning - what is it? First symbol after the doublequote.

Hide keyboard in react-native

There are a few ways, if you control of event like onPress you can use:

import { Keyboard } from 'react-native'

onClickFunction = () => {
     Keyboard.dismiss()
}

if you want to close the keyboard when the use scrolling:

<ScrollView keyboardDismissMode={'on-drag'}>
     //content
</ScrollView>

More option is when the user clicks outside the keyboard:

<KeyboardAvoidingView behavior='padding' style={{ flex: 1}}>
    //inputs and other content
</KeyboardAvoidingView>

Disable-web-security in Chrome 48+

The chosen answer is good, but for those who are still struggling with what they are talking about(your first time dealing with this issue), the following worked for me.

I created a new shortcut to Chrome on my desktop, right clicked it, and set the "Target" field to the following,

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chromedev"

The directory can be anything you want, I decided to make an empty folder called chrome dev in my C: directory. It has nothing to do where chrome is installed on your computer. It's just a fluff type thing.

This link also has clear directions for other OSes. How to disable web securityin Chrome

Java generics - ArrayList initialization

Think of the ? as to mean "unknown". Thus, "ArrayList<? extends Object>" is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3) would be putting something you know, into an unknown. I.e 'Forgetting'.

Change :hover CSS properties with JavaScript

Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

How to have git log show filenames like svn log -v

NOTE: git whatchanged is deprecated, use git log instead

New users are encouraged to use git-log[1] instead. The whatchanged command is essentially the same as git-log[1] but defaults to show the raw format diff output and to skip merges.

The command is kept primarily for historical reasons; fingers of many people who learned Git long before git log was invented by reading Linux kernel mailing list are trained to type it.


You can use the command git whatchanged --stat to get a list of files that changed in each commit (along with the commit message).

References

How can I force WebKit to redraw/repaint to propagate style changes?

For some reason I couldn't get danorton's answer to work, I could see what it was supposed to do so I tweaked it a little bit to this:

$('#foo').css('display', 'none').height();
$('#foo').css('display', 'block');

and it worked for me.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

I encountered the same issue when trying to use Cordova. Turns out I already had brew, try which brew, but it was outdated. So, I had to update it first:

  1. Update brew: brew update
  2. Install Apache Ant: brew install ant

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

In PHP, how can I add an object element to an array?

Something like:

class TestClass {
private $var1;
private $var2;

private function TestClass($var1, $var2){
    $this->var1 = $var1;
    $this->var2 = $var2;
}

public static function create($var1, $var2){
    if (is_numeric($var1)){
        return new TestClass($var1, $var2);
    }
    else return NULL;
}
}

$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");

print_r($myArray);

$myArray = array_filter($myArray, function($e){ return !is_null($e);});

print_r($myArray);

I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.

Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

Get the selected value in a dropdown using jQuery.

The above solutions didn't work for me. Here is what I finally came up with:

$( "#ddl" ).find( "option:selected" ).text();           // Text
$( "#ddl" ).find( "option:selected" ).prop("value");    // Value

Replace specific text with a redacted version using Python

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

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

Example:

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

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

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

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

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

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

Then:

import re, random

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

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

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.