This is due to the series df[cat]
containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna
operation.
In other words
pandas data type 'Object' indicates mixed types rather than str type
so using the following line:
df[cat] = le.fit_transform(df[cat].astype(str))
should help
The algorithm has 4 simple steps:
Code for the algorithm in python:
def my_sort(A):
p=A[0] #determine pivot element.
left=[] #create left array
right=[] #create right array
for i in range(1,len(A)):
#if cur elem is less than pivot, add elem in left array
if A[i]< p:
left.append(A[i])
#the recurssion will occur only if the left array is atleast half the size of original array
if len(left)>1 and len(left)>=len(A)//2:
left=my_sort(left) #recursive call
elif A[i]>p:
right.append(A[i]) #if elem is greater than pivot, append it to right array
if len(right)>1 and len(right)>=len(A)//2: # recurssion will occur only if length of right array is atleast the size of original array
right=my_sort(right)
A=left+[p]+right #append all three part of the array into one and return it
return A
my_sort([12,4,5,6,7,3,1,15])
Carry on with this algorithm recursively with the left and right parts.
You can use Tikz/pgfplots for creating animations in beamer. http://www.texample.net/tikz/examples/tag/animations/
Quicksort is usually the fastest on average, but It has some pretty nasty worst-case behaviors. So if you have to guarantee no bad data gives you O(N^2)
, you should avoid it.
Merge-sort uses extra memory, but is particularly suitable for external sorting (i.e. huge files that don't fit into memory).
Heap-sort can sort in-place and doesn't have the worst case quadratic behavior, but on average is slower than quicksort in most cases.
Where only integers in a restricted range are involved, you can use some kind of radix sort to make it very fast.
In 99% of the cases, you'll be fine with the library sorts, which are usually based on quicksort.
For those using CodeIgniter, there's a built-in Date Helper function called timezone_menu. These:
$this->load->helper('date');
echo timezone_menu('GMT', 'form-control', 'dropdown-name', ['id' => 'ci-timezone']);
Produce the following output:
<select name="dropdown-name" class="form-control" id="ci-timezone">
<option value="UM12">(UTC -12:00) Baker/Howland Island</option>
<option value="UM11">(UTC -11:00) Niue</option>
<option value="UM10">(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti</option>
<option value="UM95">(UTC -9:30) Marquesas Islands</option>
<option value="UM9">(UTC -9:00) Alaska Standard Time, Gambier Islands</option>
<option value="UM8">(UTC -8:00) Pacific Standard Time, Clipperton Island</option>
<option value="UM7">(UTC -7:00) Mountain Standard Time</option>
<option value="UM6">(UTC -6:00) Central Standard Time</option>
<option value="UM5">(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time</option>
<option value="UM45">(UTC -4:30) Venezuelan Standard Time</option>
<option value="UM4">(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time</option>
<option value="UM35">(UTC -3:30) Newfoundland Standard Time</option>
<option value="UM3">(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay</option>
<option value="UM2">(UTC -2:00) South Georgia/South Sandwich Islands</option>
<option value="UM1">(UTC -1:00) Azores, Cape Verde Islands</option>
<option value="UTC" selected="selected">(UTC) Greenwich Mean Time, Western European Time</option>
<option value="UP1">(UTC +1:00) Central European Time, West Africa Time</option>
<option value="UP2">(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time</option>
<option value="UP3">(UTC +3:00) Moscow Time, East Africa Time, Arabia Standard Time</option>
<option value="UP35">(UTC +3:30) Iran Standard Time</option>
<option value="UP4">(UTC +4:00) Azerbaijan Standard Time, Samara Time</option>
<option value="UP45">(UTC +4:30) Afghanistan</option>
<option value="UP5">(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time</option>
<option value="UP55">(UTC +5:30) Indian Standard Time, Sri Lanka Time</option>
<option value="UP575">(UTC +5:45) Nepal Time</option>
<option value="UP6">(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time</option>
<option value="UP65">(UTC +6:30) Cocos Islands, Myanmar</option>
<option value="UP7">(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam</option>
<option value="UP8">(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time</option>
<option value="UP875">(UTC +8:45) Australian Central Western Standard Time</option>
<option value="UP9">(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time</option>
<option value="UP95">(UTC +9:30) Australian Central Standard Time</option>
<option value="UP10">(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time</option>
<option value="UP105">(UTC +10:30) Lord Howe Island</option>
<option value="UP11">(UTC +11:00) Srednekolymsk Time, Solomon Islands, Vanuatu</option>
<option value="UP115">(UTC +11:30) Norfolk Island</option>
<option value="UP12">(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time</option>
<option value="UP1275">(UTC +12:45) Chatham Islands Standard Time</option>
<option value="UP13">(UTC +13:00) Samoa Time Zone, Phoenix Islands Time, Tonga</option>
<option value="UP14">(UTC +14:00) Line Islands</option>
</select>
Your insertion function assumes that the given array is sorted, it searches directly for the location where the new element can be inserted, usually by just looking at a few of the elements in the array.
The general sort function of an array can't take these shortcuts. Obviously it at least has to inspect all elements in the array to see if they are already correctly ordered. This fact alone makes the general sort slower than the insertion function.
A generic sort algorithm is usually on average O(n ⋅ log(n)) and depending on the implementation it might actually be the worst case if the array is already sorted, leading to complexities of O(n2). Directly searching for the insertion position instead has just a complexity of O(log(n)), so it will always be much faster.
In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess "middle of O(log(n)) elements" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.
Take a look here:
Edit: The referenced source (allexperts.com) has since closed, but here are the relevant author comments:
There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm. Below is a function for it.
Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually
0
) and the Upper Array Boundary (i.e.UBound(myArray)
.)Example:
Call QuickSort(myArray, 0, UBound(myArray))
When it's done,
myArray
will be sorted and you can do what you want with it.
(Source: archive.org)
Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
Dim pivot As Variant
Dim tmpSwap As Variant
Dim tmpLow As Long
Dim tmpHi As Long
tmpLow = inLow
tmpHi = inHi
pivot = vArray((inLow + inHi) \ 2)
While (tmpLow <= tmpHi)
While (vArray(tmpLow) < pivot And tmpLow < inHi)
tmpLow = tmpLow + 1
Wend
While (pivot < vArray(tmpHi) And tmpHi > inLow)
tmpHi = tmpHi - 1
Wend
If (tmpLow <= tmpHi) Then
tmpSwap = vArray(tmpLow)
vArray(tmpLow) = vArray(tmpHi)
vArray(tmpHi) = tmpSwap
tmpLow = tmpLow + 1
tmpHi = tmpHi - 1
End If
Wend
If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub
Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here.)
Consider time and space complexity both. For Merge sort : Time complexity : O(nlogn) , Space complexity : O(nlogn)
For Quick sort : Time complexity : O(n^2) , Space complexity : O(n)
Now, they both win in one scenerio each. But, using a random pivot you can almost always reduce Time complexity of Quick sort to O(nlogn).
Thus, Quick sort is preferred in many applications instead of Merge sort.
I know this topic is old, but I thought I could add something to it.
I could not make an Update with Select query work using SQL in MS Access 2010. I used Tomalak's suggestion to make this work. I had a screenshot, but am apparently too much of a newb on this site to be able to post it.
I was able to do this using the Query Design tool, but even as I was looking at a confirmed successful update query, Access was not able to show me the SQL that made it happen. So I could not make this work with SQL code alone.
I created and saved my select query as a separate query. In the Query Design tool, I added the table I'm trying to update the the select query I had saved (I put the unique key in the select query so it had a link between them). Just as Tomalak had suggested, I changed the Query Type to Update. I then just had to choose the fields (and designate the table) I was trying to update. In the "Update To" fields, I typed in the name of the fields from the select query I had brought in.
This format was successful and updated the original table.
The bash script "corstest" below works for me. It is based on Jun's comment above.
usage
corstest [-v] url
examples
./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *
the positive result is displayed in green
./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS
the negative result is displayed in red and blue
the -v option will show the full curl headers
corstest
#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139
#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'
#
# a colored message
# params:
# 1: l_color - the color of the message
# 2: l_msg - the message to display
#
color_msg() {
local l_color="$1"
local l_msg="$2"
echo -e "${l_color}$l_msg${endColor}"
}
#
# show the usage
#
usage() {
echo "usage: [-v] $0 url"
echo " -v |--verbose: show curl result"
exit 1
}
if [ $# -lt 1 ]
then
usage
fi
# commandline option
while [ "$1" != "" ]
do
url=$1
shift
# optionally show usage
case $url in
-v|--verbose)
verbose=true;
;;
esac
done
if [ "$verbose" = "true" ]
then
curl -s -X GET $url -H 'Cache-Control: no-cache' --head
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)
if [ $? -eq 0 ]
then
color_msg $green "$url $origin"
else
color_msg $red "$url does not support CORS"
color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi
Try updating the line to:
ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png
If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.
It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.
reg a[0:3];
This will create a 1D of array of single bit. Similarly 2D array can be created like this:
reg [0:3][0:2];
Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:
reg [0:4] a [0:3][0:2];
I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.
Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"
@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"
pause
I am pretty sure it will run for some time when you first run it :) Enjoy!
Use the S_ISDIR
macro:
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
I had this happen to me after an update to a new Xcode. Running
xcode-select --install
fixed it for me.
This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy.
// There are a few dependencies added by one of the Scala plugins that this cannot reach.
task downloadDependencies {
description "Pre-downloads *most* dependencies"
doLast {
configurations.getAsMap().each { name, config ->
println "Retrieving dependencies for $name"
try {
config.files
} catch (e) {
project.logger.info e.message // some cannot be resolved, silentlyish skip them
}
}
}
}
I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to reduce the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.
I have found a way if you know startIndex and endIndex of the elements one need to remove from ArrayList
Let al
be the original ArrayList and startIndex
,endIndex
be start and end index to be removed from the array respectively:
al.subList(startIndex, endIndex + 1).clear();
On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
You can use JSON.stringify
like:
JSON.stringify(new_tweets);
If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").
Rails.application.routes.default_url_options[:host]= 'localhost:3000'
In the developemnt.rb / test.rb, can be more concise as following:
Rails.application.configure do
# ... other config ...
routes.default_url_options[:host] = 'localhost:3000'
end
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
I have given the comparison of all three discussed above.
Using values
%timeit df['value'] = df['a'].values % df['c'].values
139 µs ± 1.91 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Without values
%timeit df['value'] = df['a']%df['c']
216 µs ± 1.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Apply function
%timeit df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1)
474 µs ± 5.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Look at the open function in Perl - especially the variants using a '|' (pipe) in the arguments. Done correctly, you'll get a file handle that you can use to read the output of the command. The back tick operators also do this.
You might also want to review whether Perl has access to the C functions that the command itself uses. For example, for ls -a
, you could use the opendir function, and then read the file names with the readdir function, and finally close the directory with (surprise) the closedir function. This has a number of benefits - precision probably being more important than speed. Using these functions, you can get the correct data even if the file names contain odd characters like newline.
From: http://www.csharp-examples.net/string-format-datetime/
string.Format("{0:t tt}", datetime); // -> "P PM" or "A AM"
for those who want some official document to confirm the behavior
Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.
https://www.gnu.org/software/make/manual/html_node/Environment.html
To delete a web property, you simply need to delete every profile within the property. Once the last profile has been deleted, the web property with cease to exist in the GA account. That's all there is to it! -- Source
declare @lastweek datetime
declare @now datetime
set @now = getdate()
set @lastweek = dateadd(day,-7,@now)
SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN @lastweek AND @now
GROUP BY URLx
ORDER BY Count DESC;
You can use $.each() to iterate over the array and locate the object you're interested in:
$.each(projects, function() {
if (this.value == "jquery-ui") {
this.desc = "Your new description";
}
});
It turns out I didn't have Microsoft visual c++ installed, installing it solved the problem for me.
I always wondered why the simplest program was:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Whereas it could be:
print "Hello World!"
Maybe this is to frighten computer science students in the first place ...
As a service
You can set this one by:
Going first to your installation directory (in my case it’s c:\xampplite
). It could be somewhere else depending on your installation. Have also my full version in c:\x2\xampp
.
Once your in the installation directory, find xampp-control.exe
and click/double-click to launch it.
You should first stop all running instances of your apache2
and mysqld
/mysql
processes to do this.
Click the checkmark next to Apache and MySQL with the header name service. It will warn you that it’s installing as a service which of course is what we like it to do. Click Yes.
Also do step 5 with MySQL. We’re almost done.
Click Start ? Run
Type services.msc (it can also be done in the control panel under administrative tools which is a way lot of click than this one). Find the Apache 2 and MySQL services.
Double click each one and set the startup type to Automatic (you will be presented with three options: Automatic, Manual, and Disabled):
net start apache2
Be warned though that any change in the services just like the registry can cause your system to stall.
Click the start button to manually start it (just for the session though). At the next restart it’ll be automated.
Do the same with MySQL.
As a startup program
Find xampp_start.exe from your installation directory.
Press Ctrl + C to copy it or right-click the file and hit copy.
Go to C:\Documents and Settings\Administrator\Start Menu\Programs\Startup and right click on it and hit Paste Shortcut.
When you restart it’ll be starting also and you’ll see something like this:
You can stop it by issuing the xampp_stop.exe
command in your installation directory.
Also worth mentioning is that if you right click again on the shortcut and hit properties, try to change the run option to minimized. This way the shortcut will be on your taskbar once started.
In your example, you can break the string into two pieces:
alert ( "Please Select file"
+ " to delete");
Or, when it's a string, as in your case, you can use a backslash as @Gumbo suggested:
alert ( "Please Select file\
to delete");
Note that this backslash approach is not necessarily preferred, and possibly not universally supported (I had trouble finding hard data on this). It is not in the ECMA 5.1 spec.
When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:
if(SuperLongConditionWhyIsThisSoLong
&& SuperLongConditionOnAnotherLine
&& SuperLongConditionOnThirdLineSheesh)
{
// launch_missiles();
}
I found the there is a certificate expired issue with:
npm set registry https://registry.npmjs.org/
So I made it http, not https :-
npm set registry http://registry.npmjs.org/
And have no problems so far.
I have been an hour with headache trying to close the infoWindow! My final (and working) option has been closing the infoWindow with a SetTimeout (a few seconds) It's not the best way... but it works easely
marker.addListener('click', function() {
infowindow.setContent(html);
infowindow.open(map, this);
setTimeout(function(){
infowindow.close();
},5000);
});
Yes.
However, if you need to use Application.DoEvents
, this is mostly an indication of a bad application design. Perhaps you'd like to do some work in a separate thread instead?
Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared
folder if shared between controllers (hence the name).
You can refer to views/partial views from another controller, by specifying the full path (including extension) like:
return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
or a relative path (no extension), based on the answer by @Max Toro
return PartialView("../ABC/XXX", zyxmodel);
BUT THIS IS NOT A GOOD IDEA ANYWAY
*Note: These are the only two syntax that work. not ABC\\XXX
or ABC/XXX
or any other variation as those are all relative paths and do not find a match.
You can use Html.Renderpartial
in your view instead, but it requires the extension as well:
Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);
Use @Html.Partial
for inline Razor syntax:
@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)
You can use the ../controller/view
syntax with no extension (again credit to @Max Toro):
@Html.Partial("../ControllerName/ViewName", modeldata)
Note: Apparently RenderPartial
is slightly faster than Partial, but that is not important.
If you want to actually call the other controller, use:
@Html.Action("action", "controller", parameters)
My personal preference is to use @Html.Action
as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).
You would normally pass just the required key values (like any other view) e.g. for your example:
@Html.Action("XXX", "ABC", new {id = model.xyzId })
This will execute the ABC.XXX
action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).
I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action
and controller
names. To that end I added this simple View
extension method to UrlHelper
so you can say return PartialView(Url.View("actionName", "controllerName"), modelData)
:
public static class UrlHelperExtension
{
/// <summary>
/// Return a view path based on an action name and controller name
/// </summary>
/// <param name="url">Context for extension method</param>
/// <param name="action">Action name</param>
/// <param name="controller">Controller name</param>
/// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
public static string View(this UrlHelper url, string action, string controller)
{
return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
}
}
Here is another way without extra modules:
I needed to guess the environment from the task name, I have a 'dev' task and a 'prod' task.
When I run gulp prod
it should be set to prod environment.
When I run gulp dev
or anything else it should be set to dev environment.
For that I just check the running task name:
devEnv = process.argv[process.argv.length-1] !== 'prod';
Here my single-line solution with GSON:
myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);
I like to use the tcomment plugin: http://www.vim.org/scripts/script.php?script_id=1173
I have mapped gc and gcc to comment a line or a highlighted block of code. It detects the file type and works really well.
Generally speaking, it's recommended to use MSI-based installations on Windows. Thus, if you're ready to invest a fair bit of time, WiX is the way to go.
If you want something which is much more simpler, go with InnoSetup.
When the Import Data box pops up click on Properties and remove the Check Mark next to Save query definition When the Import Data box comes back and your location is where you want it to be (Ex: =$I$4) click on OK and your problem will be resolved
Yes, bash
has filename completion mechanisms. I don't use them myself (too lazy to learn, and I don't find it necessary often enough to make it urgent), but the basic mechanism is to type the first few characters, and then a tab; this will extend the name as far as it can (perhaps not at all) as long as the name is unambiguous. There are a boatload of Emacs-style commands related to completion in the good ol' man page.
I ran into this issue over the past couple days. Like Omri Aharon said in their answer above, it is important to add definitions for your prop types similar to:
SomeClass.propTypes = {
someProp: PropTypes.number,
onTap: PropTypes.func,
};
Don't forget to add the prop definitions outside of your class. I would place it right below/above my class. If you are not sure what your variable type or suffix is for your PropType (ex: PropTypes.number), refer to this npm reference. To Use PropTypes, you must import the package:
import PropTypes from 'prop-types';
If you get the linting error:someProp is not required, but has no corresponding defaultProps declaration
all you have to do is either add .isRequired
to the end of your prop definition like so:
SomeClass.propTypes = {
someProp: PropTypes.number.isRequired,
onTap: PropTypes.func.isRequired,
};
OR add default prop values like so:
SomeClass.defaultProps = {
someProp: 1
};
If you are anything like me, unexperienced or unfamiliar with reactjs, you may also get this error: Must use destructuring props assignment
. To fix this error, define your props before they are used. For example:
const { someProp } = this.props;
For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string);
correctly stores the array, but $('#my-data-div').data('namesarray', names_string);
doesn't work.
<div id="my-data-div" data-namesarray='[]'></div>
var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);
By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.
#include <iostream>
using namespace std;
int Fibonacci(int);
int main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
}
int Fibonacci(int x)
{
if (x < 2){
return x;
}
return (Fibonacci (x - 1) + Fibonacci (x - 2));
}
The BETWEEN operator is inclusive.
From Books Online:
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
DateTime Caveat
NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.
e.g. to get all values within June 2016 you'd need to run:
where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')
i.e.
where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'
Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:
where myDateTime >= '20160601' AND myDateTime < '20160701'
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:
function calculate(a,b,fn) {
var c = a * 3 + b + fn(a,b);
return c;
}
function sum(a,b) {
return a+b;
}
function product(a,b) {
return a*b;
}
document.write(calculate (10,20,sum)); //80
document.write(calculate (10,20,product)); //250
Generally you can just cast the variable to become a short
.
You can also get problems like this that can be confusing. This is because the +
operator promotes them to an int
Casting the elements won't help:
You need to cast the expression:
No. There is no natural way.
In fact, one of the motivations behind having strongly typed enum class
in C++11 is to prevent their silent conversion to int
.
Here's a function that'll do it:
def totuple(a):
try:
return tuple(totuple(i) for i in a)
except TypeError:
return a
And an example:
>>> array = numpy.array(((2,2),(2,-2)))
>>> totuple(array)
((2, 2), (2, -2))
Every class in Java has the toString()
method in it by default, which is called if you pass some object of that class to System.out.println()
. By default, this call returns the className@hashcode of that object.
{
SomeClass sc = new SomeClass();
// Class @ followed by hashcode of object in Hexadecimal
System.out.println(sc);
}
You can override the toString method of a class to get different output. See this example
class A {
String s = "I am just a object";
@Override
public String toString()
{
return s;
}
}
class B {
public static void main(String args[])
{
A obj = new A();
System.out.println(obj);
}
}
For a hybrid dictionary, I use this:
List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());
It is an error generated by patch
. If you would open the .patch
file, you'd see that it's organized in a bunch of segments, so-called "hunks". Every hunk identifies corresponding pieces of code (by line numbers) in the old and new version, the differences between those pieces of code, and similarities between them (the "context").
A hunk might fail if the similarities of a hunk don't match what's in the original file. When you see this error, it is almost always because you're using a patch for the wrong version of the code you're patching. There are a few ways to work around this:
libdvdnav
that already includes the patch (best option)..patch
file for the version of libdvdnav
you're patching.libdvdnav
, and correct them according to the instructions in the patch.libdvdnav
that's closer to whatever version the .patch
file was intended for (probably a bad idea).js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:
apply_tuple = lambda f, t: f(*t)
Redefine apply_tuple
via curry
to save a lot of partial
calls in the long run:
from toolz import curry
apply_tuple = curry(apply_tuple)
Example usage:
from operator import add, eq
from toolz import thread_last
thread_last(
[(1,2), (3,4)],
(map, apply_tuple(add)),
list,
(eq, [3, 7])
)
# Prints 'True'
I had this exact same requirement, to remove duplicate objects in a array, based on duplicates on a single field. I found the code here: Javascript: Remove Duplicates from Array of Objects
So in my example, I'm removing any object from the array that has a duplicate licenseNum string value.
var arrayWithDuplicates = [
{"type":"LICENSE", "licenseNum": "12345", state:"NV"},
{"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
{"type":"LICENSE", "licenseNum": "12345", state:"OR"},
{"type":"LICENSE", "licenseNum": "10849", state:"CA"},
{"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
{"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];
function removeDuplicates(originalArray, prop) {
var newArray = [];
var lookupObject = {};
for(var i in originalArray) {
lookupObject[originalArray[i][prop]] = originalArray[i];
}
for(i in lookupObject) {
newArray.push(lookupObject[i]);
}
return newArray;
}
var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));
The results:
uniqueArray is:
[{"type":"LICENSE","licenseNum":"10849","state":"CA"},
{"type":"LICENSE","licenseNum":"12345","state":"NM"},
{"type":"LICENSE","licenseNum":"A7846","state":"CA"},
{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]
The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.
The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.
For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.
td:nth-child(3n+1) {
/* your stuff here */
}
:nth-of-type() works the same, except that it only considers element of the given type ( in the example).
This is related to this answer: https://stackoverflow.com/a/2653406/931265 Creating an object solved all of my problems.
Insert > Object > Opendocument Text
This will open a document window, paste your text, format it how you want, and close it.
The result is a figure. Right click the object, and select 'add a caption'.
You can now make cross references, create a table of figures.
The org/hamcrest/SelfDescribing class is not on the run-time classpath.
Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.
Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.
The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.
However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.
Before reconfiguring the global excludes file, you might want to check what it's currently configured to, using this command:
git config --get core.excludesfile
In my case, when I ran it I saw my global excludes file was configured to
~/.gitignore_globaland there were already a couple things listed there. So in the case of the given question, it might make sense to first check for an existing excludes file, and add the new file mask to it.
I would store the timespan.TotalSeconds in a float and then retrieve it using Timespan.FromSeconds(totalSeconds).
Depending on the resolution you need you could use TotalMilliseconds, TotalMinutes, TotalDays.
You could also adjust the precision of your float in the database.
It's not an exact value... but the nice thing about this is that it's easy to read and calculate in simple queries.
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
After installing git-extentions (http://gitextensions.github.io/) you can run .sh file from the command prompt. (No ./script.sh required, just run it like a bat/cmd file) Or you can run them in a "full" bash environment by using the MinGW Git bash shell.
I am not a great fan of Cygwin (yes I am sure it's really powerful), so running bash scripts on windows without having to install it perfect for me.
list.removeAll(Collections.singleton(null));
It will Throws UnsupportedException if you use it on Arrays.asList because it give you Immutable copy so it can not be modified. See below the code. It creates Mutable copy and will not throw any exception.
public static String[] clean(final String[] v) {
List<String> list = new ArrayList<String>(Arrays.asList(v));
list.removeAll(Collections.singleton(null));
return list.toArray(new String[list.size()]);
}
Observablecollection :Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed. You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.
Observablecollection<ItemState> itemStates = new Observablecollection<ItemState>();
for (int i = 0; i < 10; i++) {
itemStates.Add(new ItemState { Id = i.ToString() });
}
dataGridView1.DataSource = itemStates;
This is how I solved
<a href="#" >
<button type="button" class="btn btn-info">Button Text</button>
</a>
I'm not an expert but it sounds to me that this is something you could only do if you built the browser yourself - ie, not something done in a web page. I'm not sure that the sources for Chrome are publicly available (I think they are though), but the sources are what you'd probably need to change for this.
Here is example of using aggregation API. To complicate the case we're grouping by case-insensitive words from array property of the document.
db.articles.aggregate([
{
$match: {
keywords: { $not: {$size: 0} }
}
},
{ $unwind: "$keywords" },
{
$group: {
_id: {$toLower: '$keywords'},
count: { $sum: 1 }
}
},
{
$match: {
count: { $gte: 2 }
}
},
{ $sort : { count : -1} },
{ $limit : 100 }
]);
that give result such as
{ "_id" : "inflammation", "count" : 765 }
{ "_id" : "obesity", "count" : 641 }
{ "_id" : "epidemiology", "count" : 617 }
{ "_id" : "cancer", "count" : 604 }
{ "_id" : "breast cancer", "count" : 596 }
{ "_id" : "apoptosis", "count" : 570 }
{ "_id" : "children", "count" : 487 }
{ "_id" : "depression", "count" : 474 }
{ "_id" : "hiv", "count" : 468 }
{ "_id" : "prognosis", "count" : 428 }
Just for others (like me) who might have faced the above error. The solution in simple terms.
You might have missed to register your Interface and class (which implements that inteface) registration in your code.
e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"
Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below
container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();
You can simply print
it.
@a = qw(abc def hij);
print "@a";
You will got:
abc def hij
Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:
Why does ANT tell me that JAVA_HOME is wrong when it is not?
Interactively, you can display it with
help(my_func)
Or from code you can retrieve it with
my_func.__doc__
Split on your separator at most once, and take the first piece:
sep = '...'
stripped = text.split(sep, 1)[0]
You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.
dataGridView1.Columns
is probably of a length less than 5. Accessing dataGridView1.Columns[4]
then will be outside the list.
Here's an update as of Nov 2014. I find that setting method='curl'
did the trick for me (while method='auto'
, does not).
For example:
# does not work
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip')
# does not work. this appears to be the default anyway
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='auto')
# works!
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='curl')
try "configuration properties -> debugging -> environment" and set the PATH variable in run-time
In C++17, use std::to_chars
as:
std::array<char, 10> str;
std::to_chars(str.data(), str.data() + str.size(), 42);
In C++11, use std::to_string
as:
std::string s = std::to_string(number);
char const *pchar = s.c_str(); //use char const* as target type
And in C++03, what you're doing is just fine, except use const
as:
char const* pchar = temp_str.c_str(); //dont use cast
Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.
More Info
This solution is not perfect, but it gives some benefits:
First of all, here's working example, so you can test it before going further.
Installation:
Data > Validation
Prepare Data
Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:
Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.
First simple Data Validation (DV)
Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A)
On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.
Script
Paste this code into script editor:
function onEdit(event) _x000D_
{_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data1'; // name of sheet with data_x000D_
var NumOfLevels = 4; // number of levels of data validation_x000D_
var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,2]; // offsets for levels_x000D_
// ^ means offset column #4 on one position right._x000D_
_x000D_
// =====================================================================================_x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data2'; // name of sheet with data_x000D_
var NumOfLevels = 7; // number of levels of data validation_x000D_
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,1,1,1,1]; // offsets for levels_x000D_
// ===================================================================================== _x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets) _x000D_
{_x000D_
//--------------------------------------------------------------------------------------_x000D_
// The event handler, adds data validation for the input parameters_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
// =================================== key variables =================================_x000D_
//_x000D_
// ss sheet we change (TargetSheet)_x000D_
// br range to change_x000D_
// scol number of column to edit_x000D_
// srow number of row to edit _x000D_
// CurrentLevel level of drop-down, which we change_x000D_
// HeadLevel main level_x000D_
// r current cell, which was changed by user_x000D_
// X number of levels could be checked on the right_x000D_
//_x000D_
// ls Data sheet (LogSheet)_x000D_
//_x000D_
// ======================================================================================_x000D_
_x000D_
// Checks_x000D_
var ts = event.source.getActiveSheet();_x000D_
var sname = ts.getName(); _x000D_
if (sname !== TargetSheet) { return -1; } // not main sheet_x000D_
// Test if range fits_x000D_
var br = event.range;_x000D_
var scol = br.getColumn(); // the column number in which the change is made_x000D_
var srow = br.getRow() // line number in which the change is made_x000D_
var ColNum = br.getWidth();_x000D_
_x000D_
if ((scol + ColNum - 1) < lcol) { return -2; } // columns... _x000D_
if (srow < lrow) { return -3; } // rows_x000D_
// Test range is in levels_x000D_
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels _x000D_
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);_x000D_
if(CurrentLevel === 1) { return -4; } // out of data validations_x000D_
if(CurrentLevel > NumOfLevels) { return -5; } // last level _x000D_
_x000D_
_x000D_
/*_x000D_
ts - sheet with validation, sname = name of sheet_x000D_
_x000D_
NumOfLevels = 4 _x000D_
offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column_x000D_
columnsLevels = [4,5,6,8] - Columns of validation_x000D_
_x000D_
Columns 7 is skipped_x000D_
|_x000D_
1 2 3 4 5 6 7 8 9 _x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
1 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
2 | | | | v | V | ? | x | ? | | lrow = 2 - number of row where validation starts_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
3 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
4 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
| | | | |_x000D_
| | | | Currentlevel = 3 - the number of level to change_x000D_
| | | |_x000D_
| | | br - cell, user changes: scol - column, srow - row,_x000D_
| | ColNum = 1 - width _x000D_
|__|________ _.....____|_x000D_
| v_x000D_
| Drop-down lists _x000D_
|_x000D_
| lcol = 4 - number of column where validation starts_x000D_
*/_x000D_
// Constants_x000D_
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals_x000D_
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet _x000D_
var RowNum = br.getHeight();_x000D_
/* Adjust the range 'br' _x000D_
??? !_x000D_
xxx x_x000D_
xxx x _x000D_
xxx => x_x000D_
xxx x_x000D_
xxx x_x000D_
*/ _x000D_
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum); _x000D_
// Levels_x000D_
var HeadLevel = CurrentLevel - 1; // main level_x000D_
var X = NumOfLevels - CurrentLevel + 1; // number of levels left _x000D_
// determine columns on the sheet "Data"_x000D_
var KudaCol = NumOfLevels + 2;_x000D_
var KudaNado = ls.getRange(1, KudaCol); // 1 place for a formula_x000D_
var lastRow = ls.getLastRow();_x000D_
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula_x000D_
_x000D_
// ============================================================================= > loop >_x000D_
var CurrLevelBase = CurrentLevel; // remember the first current level_x000D_
_x000D_
_x000D_
_x000D_
for (var j = 1; j <= RowNum; j++) // [01] loop rows start_x000D_
{ _x000D_
// refresh first val _x000D_
var currentRow = br.getCell(j, 1).getRow(); _x000D_
loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} // [01] loop rows end_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getColumnsOffset_(offsets, lefColumn)_x000D_
{_x000D_
// Columns for all levels_x000D_
var columnsLevels = [];_x000D_
var totalOffset = 0; _x000D_
for (var i = 0, l = offsets.length; i < l; i++)_x000D_
{ _x000D_
totalOffset += offsets[i];_x000D_
columnsLevels.push(totalOffset + lefColumn - 1);_x000D_
} _x000D_
_x000D_
return columnsLevels;_x000D_
_x000D_
}_x000D_
_x000D_
function test_getCurrentLevel()_x000D_
{_x000D_
var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');_x000D_
var scol = 1;_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/_x000D_
Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxx| |xxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxxxxxxxx| _x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxx| |xxxxx| _x000D_
levels 1 2 3_x000D_
level 3_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 4 (error)_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels _x000D_
level 1 (error) _x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1 _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getCurrentLevel_(ColNum, br, scol, columnsLevels)_x000D_
{_x000D_
var colPlus = 2; // const_x000D_
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }_x000D_
var CurrentLevel = -1;_x000D_
var level = 0;_x000D_
var column = 0;_x000D_
for (var i = 0; i < ColNum; i++ )_x000D_
{_x000D_
column = br.offset(0, i).getColumn();_x000D_
level = columnsLevels.indexOf(column) + colPlus;_x000D_
if (level > CurrentLevel) { CurrentLevel = level; }_x000D_
}_x000D_
return CurrentLevel;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
for (var k = 1; k <= X; k++)_x000D_
{ _x000D_
HeadLevel = HeadLevel + k - 1; _x000D_
CurrentLevel = CurrLevelBase + k - 1;_x000D_
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);_x000D_
var SearchText = r.getValue(); // searched text _x000D_
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} _x000D_
}_x000D_
_x000D_
_x000D_
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
_x000D_
_x000D_
// if nothing is chosen!_x000D_
if (SearchText === '') // condition value =''_x000D_
{_x000D_
// kill extra data validation if there were _x000D_
// columns on the right_x000D_
if (CurrentLevel <= NumOfLevels) _x000D_
{_x000D_
for (var f = 0; f < X; f++) _x000D_
{_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]); _x000D_
// clean & get rid of validation_x000D_
cell.clear({contentsOnly: true}); _x000D_
cell.clear({validationsOnly: true});_x000D_
// exit columns loop _x000D_
}_x000D_
}_x000D_
return 0; // end loop this row _x000D_
}_x000D_
_x000D_
_x000D_
// formula for values_x000D_
var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts); _x000D_
KudaNado.setFormula(formula);_x000D_
_x000D_
_x000D_
// get response_x000D_
var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);_x000D_
var Variants = Response.length;_x000D_
_x000D_
_x000D_
// build data validation rule_x000D_
if (Variants === 0.0) // empty is found_x000D_
{_x000D_
return;_x000D_
} _x000D_
if(Variants >= 1.0) // if some variants were found_x000D_
{_x000D_
_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);_x000D_
var rule = SpreadsheetApp_x000D_
.newDataValidation()_x000D_
.requireValueInList(Response, true)_x000D_
.setAllowInvalid(false)_x000D_
.build();_x000D_
// set validation rule_x000D_
cell.setDataValidation(rule);_x000D_
} _x000D_
if (Variants === 1.0) // // set the only value_x000D_
{ _x000D_
cell.setValue(Response[0]);_x000D_
SearchText = null;_x000D_
Response = null;_x000D_
return X; // continue doing DV_x000D_
} // the only value_x000D_
_x000D_
return 0; // end DV in this row_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)_x000D_
{_x000D_
_x000D_
var checkVals = [];_x000D_
var Offs = CurrentLevel - 2;_x000D_
var values = [];_x000D_
// get values and display values for a formula_x000D_
for (var s = 0; s <= Offs; s++)_x000D_
{_x000D_
var checkR = ts.getRange(currentRow, columnsLevels[s]);_x000D_
values.push(checkR.getValue());_x000D_
} _x000D_
_x000D_
var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."_x000D_
var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84_x000D_
_x000D_
var mathOpPlusVal = ''; _x000D_
var value = '';_x000D_
_x000D_
// loop levels for multiple conditions _x000D_
for (var i = 0; i < CurrentLevel - 1; i++) { _x000D_
formula += FormulaSplitter; // =unique(filter(A2:A84;_x000D_
LookCol = colName(i);_x000D_
_x000D_
value = values[i];_x000D_
_x000D_
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"_x000D_
_x000D_
if ( Array.isArray(mathOpPlusVal) )_x000D_
{_x000D_
formula += mathOpPlusVal[0];_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84_x000D_
formula += mathOpPlusVal[1];_x000D_
}_x000D_
else_x000D_
{_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84_x000D_
formula += mathOpPlusVal;_x000D_
}_x000D_
_x000D_
_x000D_
} _x000D_
_x000D_
formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))_x000D_
_x000D_
return formula;_x000D_
}_x000D_
_x000D_
_x000D_
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)_x000D_
{_x000D_
var result = '';_x000D_
var splinter = ''; _x000D_
_x000D_
var type = typeof value;_x000D_
_x000D_
_x000D_
// strings_x000D_
if (type === 'string') return '="' + value + '"';_x000D_
// date_x000D_
if(value instanceof Date)_x000D_
{_x000D_
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+' _x000D_
+ 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)']; _x000D_
} _x000D_
// numbers_x000D_
if (type === 'number')_x000D_
{_x000D_
if (ReplaceCommas)_x000D_
{_x000D_
return '+0=' + value.toString().replace('.', ','); _x000D_
}_x000D_
else_x000D_
{_x000D_
return '+0=' + value;_x000D_
}_x000D_
}_x000D_
// booleans_x000D_
if (type === 'boolean')_x000D_
{_x000D_
return '=' + value;_x000D_
} _x000D_
// other_x000D_
return '=' + value;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getResponse_(allRange, l, ReplaceCommas)_x000D_
{_x000D_
var data = allRange.getValues();_x000D_
var data_ = allRange.getDisplayValues();_x000D_
_x000D_
var response = [];_x000D_
var val = '';_x000D_
for (var i = 0; i < l; i++)_x000D_
{_x000D_
val = data[i][0];_x000D_
if (val !== '') _x000D_
{_x000D_
var type = typeof val;_x000D_
if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);_x000D_
if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')_x000D_
response.push(val); _x000D_
}_x000D_
}_x000D_
_x000D_
return response; _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function colName(n) {_x000D_
var ordA = 'a'.charCodeAt(0);_x000D_
var ordZ = 'z'.charCodeAt(0);_x000D_
_x000D_
var len = ordZ - ordA + 1;_x000D_
_x000D_
var s = "";_x000D_
while(n >= 0) {_x000D_
s = String.fromCharCode(n % len + ordA) + s;_x000D_
n = Math.floor(n / len) - 1;_x000D_
}_x000D_
return s; _x000D_
}_x000D_
_x000D_
_x000D_
function getDecimalMarkIsCommaLocals() {_x000D_
_x000D_
_x000D_
// list of Locals Decimal mark = comma_x000D_
var LANGUAGE_BY_LOCALE = {_x000D_
af_NA: "Afrikaans (Namibia)",_x000D_
af_ZA: "Afrikaans (South Africa)",_x000D_
af: "Afrikaans",_x000D_
sq_AL: "Albanian (Albania)",_x000D_
sq: "Albanian",_x000D_
ar_DZ: "Arabic (Algeria)",_x000D_
ar_BH: "Arabic (Bahrain)",_x000D_
ar_EG: "Arabic (Egypt)",_x000D_
ar_IQ: "Arabic (Iraq)",_x000D_
ar_JO: "Arabic (Jordan)",_x000D_
ar_KW: "Arabic (Kuwait)",_x000D_
ar_LB: "Arabic (Lebanon)",_x000D_
ar_LY: "Arabic (Libya)",_x000D_
ar_MA: "Arabic (Morocco)",_x000D_
ar_OM: "Arabic (Oman)",_x000D_
ar_QA: "Arabic (Qatar)",_x000D_
ar_SA: "Arabic (Saudi Arabia)",_x000D_
ar_SD: "Arabic (Sudan)",_x000D_
ar_SY: "Arabic (Syria)",_x000D_
ar_TN: "Arabic (Tunisia)",_x000D_
ar_AE: "Arabic (United Arab Emirates)",_x000D_
ar_YE: "Arabic (Yemen)",_x000D_
ar: "Arabic",_x000D_
hy_AM: "Armenian (Armenia)",_x000D_
hy: "Armenian",_x000D_
eu_ES: "Basque (Spain)",_x000D_
eu: "Basque",_x000D_
be_BY: "Belarusian (Belarus)",_x000D_
be: "Belarusian",_x000D_
bg_BG: "Bulgarian (Bulgaria)",_x000D_
bg: "Bulgarian",_x000D_
ca_ES: "Catalan (Spain)",_x000D_
ca: "Catalan",_x000D_
tzm_Latn: "Central Morocco Tamazight (Latin)",_x000D_
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",_x000D_
tzm: "Central Morocco Tamazight",_x000D_
da_DK: "Danish (Denmark)",_x000D_
da: "Danish",_x000D_
nl_BE: "Dutch (Belgium)",_x000D_
nl_NL: "Dutch (Netherlands)",_x000D_
nl: "Dutch",_x000D_
et_EE: "Estonian (Estonia)",_x000D_
et: "Estonian",_x000D_
fi_FI: "Finnish (Finland)",_x000D_
fi: "Finnish",_x000D_
fr_BE: "French (Belgium)",_x000D_
fr_BJ: "French (Benin)",_x000D_
fr_BF: "French (Burkina Faso)",_x000D_
fr_BI: "French (Burundi)",_x000D_
fr_CM: "French (Cameroon)",_x000D_
fr_CA: "French (Canada)",_x000D_
fr_CF: "French (Central African Republic)",_x000D_
fr_TD: "French (Chad)",_x000D_
fr_KM: "French (Comoros)",_x000D_
fr_CG: "French (Congo - Brazzaville)",_x000D_
fr_CD: "French (Congo - Kinshasa)",_x000D_
fr_CI: "French (Côte d’Ivoire)",_x000D_
fr_DJ: "French (Djibouti)",_x000D_
fr_GQ: "French (Equatorial Guinea)",_x000D_
fr_FR: "French (France)",_x000D_
fr_GA: "French (Gabon)",_x000D_
fr_GP: "French (Guadeloupe)",_x000D_
fr_GN: "French (Guinea)",_x000D_
fr_LU: "French (Luxembourg)",_x000D_
fr_MG: "French (Madagascar)",_x000D_
fr_ML: "French (Mali)",_x000D_
fr_MQ: "French (Martinique)",_x000D_
fr_MC: "French (Monaco)",_x000D_
fr_NE: "French (Niger)",_x000D_
fr_RW: "French (Rwanda)",_x000D_
fr_RE: "French (Réunion)",_x000D_
fr_BL: "French (Saint Barthélemy)",_x000D_
fr_MF: "French (Saint Martin)",_x000D_
fr_SN: "French (Senegal)",_x000D_
fr_CH: "French (Switzerland)",_x000D_
fr_TG: "French (Togo)",_x000D_
fr: "French",_x000D_
gl_ES: "Galician (Spain)",_x000D_
gl: "Galician",_x000D_
ka_GE: "Georgian (Georgia)",_x000D_
ka: "Georgian",_x000D_
de_AT: "German (Austria)",_x000D_
de_BE: "German (Belgium)",_x000D_
de_DE: "German (Germany)",_x000D_
de_LI: "German (Liechtenstein)",_x000D_
de_LU: "German (Luxembourg)",_x000D_
de_CH: "German (Switzerland)",_x000D_
de: "German",_x000D_
el_CY: "Greek (Cyprus)",_x000D_
el_GR: "Greek (Greece)",_x000D_
el: "Greek",_x000D_
hu_HU: "Hungarian (Hungary)",_x000D_
hu: "Hungarian",_x000D_
is_IS: "Icelandic (Iceland)",_x000D_
is: "Icelandic",_x000D_
id_ID: "Indonesian (Indonesia)",_x000D_
id: "Indonesian",_x000D_
it_IT: "Italian (Italy)",_x000D_
it_CH: "Italian (Switzerland)",_x000D_
it: "Italian",_x000D_
kab_DZ: "Kabyle (Algeria)",_x000D_
kab: "Kabyle",_x000D_
kl_GL: "Kalaallisut (Greenland)",_x000D_
kl: "Kalaallisut",_x000D_
lv_LV: "Latvian (Latvia)",_x000D_
lv: "Latvian",_x000D_
lt_LT: "Lithuanian (Lithuania)",_x000D_
lt: "Lithuanian",_x000D_
mk_MK: "Macedonian (Macedonia)",_x000D_
mk: "Macedonian",_x000D_
naq_NA: "Nama (Namibia)",_x000D_
naq: "Nama",_x000D_
pl_PL: "Polish (Poland)",_x000D_
pl: "Polish",_x000D_
pt_BR: "Portuguese (Brazil)",_x000D_
pt_GW: "Portuguese (Guinea-Bissau)",_x000D_
pt_MZ: "Portuguese (Mozambique)",_x000D_
pt_PT: "Portuguese (Portugal)",_x000D_
pt: "Portuguese",_x000D_
ro_MD: "Romanian (Moldova)",_x000D_
ro_RO: "Romanian (Romania)",_x000D_
ro: "Romanian",_x000D_
ru_MD: "Russian (Moldova)",_x000D_
ru_RU: "Russian (Russia)",_x000D_
ru_UA: "Russian (Ukraine)",_x000D_
ru: "Russian",_x000D_
seh_MZ: "Sena (Mozambique)",_x000D_
seh: "Sena",_x000D_
sk_SK: "Slovak (Slovakia)",_x000D_
sk: "Slovak",_x000D_
sl_SI: "Slovenian (Slovenia)",_x000D_
sl: "Slovenian",_x000D_
es_AR: "Spanish (Argentina)",_x000D_
es_BO: "Spanish (Bolivia)",_x000D_
es_CL: "Spanish (Chile)",_x000D_
es_CO: "Spanish (Colombia)",_x000D_
es_CR: "Spanish (Costa Rica)",_x000D_
es_DO: "Spanish (Dominican Republic)",_x000D_
es_EC: "Spanish (Ecuador)",_x000D_
es_SV: "Spanish (El Salvador)",_x000D_
es_GQ: "Spanish (Equatorial Guinea)",_x000D_
es_GT: "Spanish (Guatemala)",_x000D_
es_HN: "Spanish (Honduras)",_x000D_
es_419: "Spanish (Latin America)",_x000D_
es_MX: "Spanish (Mexico)",_x000D_
es_NI: "Spanish (Nicaragua)",_x000D_
es_PA: "Spanish (Panama)",_x000D_
es_PY: "Spanish (Paraguay)",_x000D_
es_PE: "Spanish (Peru)",_x000D_
es_PR: "Spanish (Puerto Rico)",_x000D_
es_ES: "Spanish (Spain)",_x000D_
es_US: "Spanish (United States)",_x000D_
es_UY: "Spanish (Uruguay)",_x000D_
es_VE: "Spanish (Venezuela)",_x000D_
es: "Spanish",_x000D_
sv_FI: "Swedish (Finland)",_x000D_
sv_SE: "Swedish (Sweden)",_x000D_
sv: "Swedish",_x000D_
tr_TR: "Turkish (Turkey)",_x000D_
tr: "Turkish",_x000D_
uk_UA: "Ukrainian (Ukraine)",_x000D_
uk: "Ukrainian",_x000D_
vi_VN: "Vietnamese (Vietnam)",_x000D_
vi: "Vietnamese"_x000D_
}_x000D_
_x000D_
_x000D_
var SS = SpreadsheetApp.getActiveSpreadsheet();_x000D_
var LocalS = SS.getSpreadsheetLocale();_x000D_
_x000D_
_x000D_
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {_x000D_
return false;_x000D_
_x000D_
}_x000D_
//Logger.log(true);_x000D_
return true;_x000D_
}_x000D_
_x000D_
/*_x000D_
function ReplaceDotsToCommas(dataIn) {_x000D_
var dataOut = dataIn.map(function(num) {_x000D_
if (isNaN(num)) {_x000D_
return num;_x000D_
} _x000D_
num = num.toString();_x000D_
return num.replace(".", ",");_x000D_
});_x000D_
return dataOut;_x000D_
}_x000D_
*/
_x000D_
Here's set of variables that are to be changed, you'll find them in script:
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.
<head>
<style>
p{text-align:center;margin-left:20px;}
</style>
</head>
<body>
<h1>JavaScript patterns</h1>
<p id="demo"></p>
<script>
var x=function(n){
document.write("<center>");
var c="";
for(var i=0; i<n; i++){
c=c+"#";
document.write(c);
document.write("<br>");
}
for(var k=n;k>0;k--){
for(var j=0; j<(k-1); j++){
document.write("#");
}
document.write("<br>");
}
}
document.getElementById("demo").innerHTML = x(10);
</script>
I really like the philosophy of the ezSQL database library, which wraps the native SQL methods in an easier-to-use interface.
Fetching a single value from the database is trivial:
$id = $db->get_var("SELECT id FROM games WHERE ...");
It also makes it easy to fetch a single row, column, or set of rows.
you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down
ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP
Follow these steps :
Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot :
You can transition background-image
. Use the CSS below on the img
element:
-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;
This is supported natively by Chrome, Opera and Safari. Firefox hasn't implemented it yet (bugzil.la). Not sure about IE.
You can use dd to extract arbitrary chunks of bytes.
For example,
dd skip=1234 count=5 bs=1
would copy bytes 1235 to 1239 from its input to its output, and discard the rest.
To just get the first five bytes from standard input, do:
dd count=5 bs=1
Note that, if you want to specify the input file name, dd has old-fashioned argument parsing, so you would do:
dd count=5 bs=1 if=filename
Note also that dd verbosely announces what it did, so to toss that away, do:
dd count=5 bs=1 2>&-
or
dd count=5 bs=1 2>/dev/null
If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply
as follows:
vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
var1*var2
}
mapply(mult_one,vars1,vars2)
which gives you:
> mapply(mult_one,vars1,vars2)
[1] 10 40 90
try this one
$(function () {
setTimeout(function () {
if ($(".alert").is(":visible")){
//you may add animate.css class for fancy fadeout
$(".alert").fadeOut("fast");
}
}, 3000)
});
To make things neat, I take Hayden's solution but make a small function out of it.
def create_value(row):
if row['Action'] == 'Sell':
return row['Prices'] * row['Amount']
else:
return -row['Prices']*row['Amount']
so that when we want to apply the function to our dataframe, we can do..
df['Value'] = df.apply(lambda row: create_value(row), axis=1)
...and any modifications only need to occur in the small function itself.
Concise, Readable, and Neat!
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
This should be the answer you are looking for
EmployeeInfo.objects.update_or_create(
#id or any primary key:value to search for
identifier=your_id,
#if found update with the following or save/create if not found
defaults={'name':'your_name'}
)
In SqlServer2005 you can do the following:
DECLARE @Limit INT
DECLARE @Offset INT
SET @Offset = 120000
SET @Limit = 10
SELECT
*
FROM
(
SELECT
row_number()
OVER
(ORDER BY column) AS rownum, column2, column3, .... columnX
FROM
table
) AS A
WHERE
A.rownum BETWEEN (@Offset) AND (@Offset + @Limit-1)
Do you mean full calendar days, or groups of 24 hours?
For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:
days = (a - b).days
For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:
roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
As simple as like this,
make sure to change example.com to your domain (or IP), and 8080 to your Node.js application port:
server {
listen 80;
server_name example.com;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass "http://127.0.0.1:8080";
}
}
Source: https://eladnava.com/binding-nodejs-port-80-using-nginx/
Reflection e.g.:
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
}
PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.
getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
Call getActivity() method inside the onActivityCreated()
value="<?php echo htmlspecialchars($name); ?>"
To account for milliseconds and the user's time zone, use the following:
var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable
border: 0
should be enough, but if it isn't, perhaps the button's browser-default styling in interfering. Have you tried setting appearance
to none
(e.g. -webkit-appearance: none
)
Yes it is, and you can also use it like this
<button>Click here to<br/> start playing</button>
if you want to make the break yourself.
I see that people have already talked about class path. Since there is no accepted answer, I assume it is not related to class path. So I would like to add that, not having package directive can also lead to class not found errors.
select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;
That's the simplest one without doing sub queries
Refered to the answers given above (I do not have enough reputation to refer separately to individual solutions, hence I do this collectively in this place), I want to supplement them with some important suggestions:
docker-compose you can install from the repository (if you have this package in the repository, if not you can adding to system a repository with this package) or download binary with use curl - totourial on the official website of the project - src: https://docs.docker.com/compose/install /
docker-compose from the repository is in version 1.8.0 (at least at me). This docker-compose version does not support configuration files in version 3. It only has version = <2 support. Inthe official site of the project is a recommendation to use container configuration in version 3 - src: https://docs.docker.com/compose/compose-file / compose-versioning /. From my own experience with work in the docker I recommend using container configurations in version 3 - there are more configuration options to use than in versions <3. If you want to use the configurations configurations in version 3 you have to do update / install docker-compose to the version of at least 1.17 - preferably the latest stable. The official site of the project is toturial how to do this process - src: https://docs.docker.com/compose/install/
when you try to manually remove the old docker-compose binaries, you can have information about the missing file in the default path /usr/local/bin/docker-compose
. At my case, docker-compose was in the default path /usr/bin/docker-compose. In this case, I suggest you use the find tool in your system to find binary file docker-compose - example syntax: sudo find / -name 'docker-compose'
. It helped me. Thanks to this, I removed the old docker-compose version and added the stable to the system - I use the curl tool to download binary file docker-compose, putting it in the right path and giving it the right permissions - all this process has been described in the posts above.
Regards, Adam
My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.
The simplest is just
string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();
The advantage(s) of this (over ParameterizedThreadStart
) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object
all the time.
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.
I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.
You can use gmmktime function without arguments to obtain the current UTC timestamp:
$time = gmmktime();
echo date("Y-m-d H:i:s", $time);
gmmktime will only work if your server time is using UTC. For example, my server is set to US/Pacific. the listed function above echos back Pacific time.
I think you're using the wrong approach. You should set the value
attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.
ie.
<input type="radio" runat="server" name="testGroup" value="test2" />
return $('input:radio[name=testGroup]:checked').val() == 'test2';
The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for
my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]
You can also check if a particular docker container is running or not using following command:
docker inspect postgres | grep "Running"
This command will check if for example my postgres container is running or not and will return output as "Running": true
Hope this helps.
Assuming that you have a data frame called students
, you can select individual rows or columns using the bracket syntax, like this:
students[1,2]
would select row 1 and column 2, the result here would be a single cell.students[1,]
would select all of row 1, students[,2]
would select all of column 2.If you'd like to select multiple rows or columns, use a list of values, like this:
students[c(1,3,4),]
would select rows 1, 3 and 4, students[c("stu1", "stu2"),]
would select rows named stu1
and stu2
.Hope I could help.
You might want to check out RFC 6570. This URI Template spec shows many examples of how urls can contain parameters.
SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
OR DATEDIFF(D,create_date, GETDATE()) < 7)
One hour is 3600sec, one minute is 60sec so why not:
<?php
$init = 685;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
echo "$hours:$minutes:$seconds";
?>
which produces:
$ php file.php
0:11:25
(I've not tested this much, so there might be errors with floor or so)
I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.
But in this case, it works, because the std::vector
is a class, and classes, like structs, can (and will) be copied to the callers context. [Actually, most compilers will optimise out this particular type of copy using something called "Return Value Optimisation", specifically introduced to avoid copying large objects when they are returned from a function, but that's an optimisation, and from a programmers perspective, it will behave as if the assignment constructor was called for the object]
As long as you don't return a pointer or a reference to something that is within the function returning, you are fine.
If you have:
Do this:
mydict = {y[0]: y[1] for y in [x.split(",") for x in open('file.csv').read().split('\n') if x]}
It uses list comprehension to split lines and the last "if x" is used to ignore blank line (usually at the end) which is then unpacked into a dict using dictionary comprehension.
Since the data is not free, you can use this Bloomberg API Emulator (disclaimer: it's my project) to learn how to send requests and make subscriptions. This emulator looks and acts just like the real Bloomberg API, although it doesn't return real data. In my time developing applications that use the Bloomberg API, I rarely care about the actual data that I'm handling; I care about how to retrieve data.
If you want to learn how to use the Bloomberg API give it a try. If you want to test out your code without an account, use this. A Bloomberg account costs about $2,000 a month, so you can save a lot with this project.
The emulator now supports Java and C++ in addition to C#.
C#, C++, and Java:
You can disable pager for commands that don't recognize --no-pager
flag.
git config --global pager.<command> false
I disable for log aliases and set specific quantity to return.
git config --global pager.log false
The accepted answer is out of date. Some of the suggestions were already incorporated in the package, and I was still getting the error about missing config-win.h & mysqlclient.lib.
Install mysql-connector-c-6.0.2-win32.msi
There's a zip file for the conenctor too but that didn't work because
mysqlclient.lib
is inlib
directory whereas the installer expects it inlib/opt
. Instead of hacking site.cfg or setup_windows.py, the msi does the job.
pip install mysql-python
P.S. Since I don't use MySQL anymore, my answer may be out of date as well.
So this has happened a couple of times just recently. As a .Net dev, using VisualStudio I changed my build name from SomeThing
to Something
as the DLL name but this does not change the .csproj file which stays SomeThing.csproj
The Dockerfile uses linux case-sensitive filenames, so the newly autogenerated Dockerfile was trying to copy Something.csproj
which it couldn't find. So manually renaming that file (making it lowercase) got it all working
But...here's a cautionary warning. This filename change on my Windows laptop does not get picked up by Git so the repo source was still SomeThing.csproj
on the repo and during the CI/CD process, the Docker build failed for the same reasons...
I had to change the filename directly as a commit on the repo....nasty little workaround but got me going
tl;dr If on Windows O/S check for filename case sensitivity and be aware local file renames do not get picked up as Git change so make sure your repo is also modified if using CI/CD
Create screen from Terminal:
screen -S <screen_name>
To see list of screens:
<screen -ls> or <screen -list>
To go to particular screen:
<screen -x screen_name>
<screen -r screen_name>
Inside screen
To Terminate screen:
give ctrl+d screen will get terminated
To Detach screen:
give <ctrl+ad>or <screen -d >screen will get detached
To reattach screen:
screen -x <screen_name> or screen -r <screen_name>
To kill a screen from Terminal:
<screen -X -S screen_name quit>
or
<screen -X -S screen_name kill>
You can use screen_name or process_id to execute commands.
F5 is a standard page reload.
and
Ctrl + F5 refreshes the page by clearing the cached content of the page.
Having the cursor in the address field and pressing Enter will also do the same as Ctrl + F5.
Create enum like this:
//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}
Create method like:
func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
throw spendingError.limit
}
return morningSpending + eveningSpending
}
Now check error is there or not and handle it:
do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}
This is example code that works for sure. It took me a day to make this to read a set of objects from a REST service:
RootObject is the type of the object I'm reading from the REST service.
string url = @"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<RootObject>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<RootObject> countries = (IEnumerable<RootObject>)serializer.ReadObject(memo);
}
Console.Read();
Try this :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<style type="text/css">
#btn_s{
width:100px;
}
#btn_i {
width:125px;
}
#formbox {
width:400px;
margin:auto 0;
text-align: center;
}
</style>
</head>
<body>
<form method="post" action="">
<div id="formbox">
<input value="Search" title="Search" type="submit" id="btn_s">
<input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
</div>
</form>
</body>
This has 2 examples, you can use the one that fits best in your situation.
text-align:center
on the parent container, or create a container for this.auto
left and right margins to center it in the parent container.note that auto
is used with single blocks to center them in the parent space by distrubuting the empty space to the left and right.
../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.
Go to web.xml
add <element>
before
<web-app>
and close </element>
after </web-app>
should be somethings like this
<?xml version="1.0" encoding="UTF-8"?>
<element>
<web-app>
....
</web-app>
</element>
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();
Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.
I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8
and i changed the content type to application/javascript
It started working.
Microsoft SQL Server Management Studio 2008 R2:
In a query editor, if you highlight the text of table name (ex dbo.MyTable) and hit ALT+F1, you'll get a list of column names, type, length, etc.
ALT+F1 while you've highlighted dbo.MyTable
is the equivalent of running EXEC sp_help 'dbo.MyTable'
according to this site
I can't get the variations on querying INFORMATION_SCHEMA.COLUMNS to work, so I use this instead.
I think things would be easier if you code your success
function to load the appropriate page instead of returning true
or false
.
For example instead of returning true
you could do:
window.location="appropriate page";
That way when the success function is called the page gets redirected.
From the Twitter FAQ:
Most integrations with the API will require you to identify your application to Twitter by way of an API key. On the Twitter platform, the term "API key" usually refers to what's called an OAuth consumer key. This string identifies your application when making requests to the API. In OAuth 1.0a, your "API keys" probably refer to the combination of this consumer key and the "consumer secret," a string that is used to securely "sign" your requests to Twitter.
If you only need the indices, you could try numpy.ndindex
:
>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
You can use SublimeREPL (you need to have Package Control installed first).
Use the ensure_ascii=False
switch to json.dumps()
, then encode the value to UTF-8 manually:
>>> json_string = json.dumps("??? ????", ensure_ascii=False).encode('utf8')
>>> json_string
b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
>>> print(json_string.decode())
"??? ????"
If you are writing to a file, just use json.dump()
and leave it to the file object to encode:
with open('filename', 'w', encoding='utf8') as json_file:
json.dump("??? ????", json_file, ensure_ascii=False)
Caveats for Python 2
For Python 2, there are some more caveats to take into account. If you are writing this to a file, you can use io.open()
instead of open()
to produce a file object that encodes Unicode values for you as you write, then use json.dump()
instead to write to that file:
with io.open('filename', 'w', encoding='utf8') as json_file:
json.dump(u"??? ????", json_file, ensure_ascii=False)
Do note that there is a bug in the json
module where the ensure_ascii=False
flag can produce a mix of unicode
and str
objects. The workaround for Python 2 then is:
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(u"??? ????", ensure_ascii=False)
# unicode(data) auto-decodes data to unicode if str
json_file.write(unicode(data))
In Python 2, when using byte strings (type str
), encoded to UTF-8, make sure to also set the encoding
keyword:
>>> d={ 1: "??? ????", 2: u"??? ????" }
>>> d
{1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}
>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
>>> s
u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
>>> json.loads(s)['1']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> json.loads(s)['2']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> print json.loads(s)['1']
??? ????
>>> print json.loads(s)['2']
??? ????
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
Recommend using the cors express module. This allows you to whitelist domains, allow/restrict domains specifically to routes, etc.,
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
You Can Remove Char using below Line ,
:- First check That String has enough char to remove ,like
string temp="Hello Stack overflow";
if(temp.Length>10)
{
string textIWant = temp.Remove(0, 10);
}
git reset
and git clean
can be overkill in some situations (and be a huge waste of time).
If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch>
is the best option.
If you're like me, your other option was to clean and perform a --hard reset
then recompile your project.
A pkg-config file describes all necessary compile-time and link-time flags and dependencies needed to use a library.
pkg-config --static --libs glfw3
shows me that
-L/usr/local/lib -lglfw3 -lrt -lXrandr -lXinerama -lXi -lXcursor -lGL -lm -ldl -lXrender -ldrm -lXdamage -lX11-xcb -lxcb-glx -lxcb-dri2 -lxcb-dri3 -lxcb-present -lxcb-sync -lxshmfence -lXxf86vm -lXfixes -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp
I don't know if all these libs are actually necessary for compiling but for me it works...
The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).
For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.
The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.
Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".
In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".
Have you seen CodeIgniter's Language library?
The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.
In your CodeIgniter system folder you'll find one called language containing sets of language files. You can create your own language files as needed in order to display error and other messages in other languages.
Language files are typically stored in your system/language directory. Alternately you can create a folder called language inside your application folder and store them there. CodeIgniter will look first in your application/language directory. If the directory does not exist or the specified language is not located there CI will instead look in your global system/language folder.
In your case...
polish_lang.php
and english_lang.php
inside application/language/polish
$lang['hello'] = "Witaj";
$this->lang->load('polish_lang', 'polish');
$this->lang->line('hello');
Just store the return value of this function in a variable so you can use it in your view.Repeat the steps for the english language and all other languages you need.
I was not content with any of the answers on this page, so I fiddled with this myself for a bit. I came up with the following
angular.module('showcase', []).controller('Ctrl', function() {_x000D_
var vm = this;_x000D_
vm.focusParent = function(event) {_x000D_
angular.element(event.target).parent().addClass('focus');_x000D_
};_x000D_
_x000D_
vm.blurParent = function(event) {_x000D_
angular.element(event.target).parent().removeClass('focus');_x000D_
};_x000D_
});
_x000D_
.input-merge .col-xs-2,_x000D_
.input-merge .col-xs-4,_x000D_
.input-merge .col-xs-6 {_x000D_
padding-left: 0;_x000D_
padding-right: 0;_x000D_
}_x000D_
.input-merge div:first-child .form-control {_x000D_
border-top-right-radius: 0;_x000D_
border-bottom-right-radius: 0;_x000D_
}_x000D_
.input-merge div:last-child .form-control {_x000D_
border-top-left-radius: 0;_x000D_
border-bottom-left-radius: 0;_x000D_
}_x000D_
.input-merge div:not(:first-child) {_x000D_
margin-left: -1px;_x000D_
}_x000D_
.input-merge div:not(:first-child):not(:last-child) .form-control {_x000D_
border-radius: 0;_x000D_
}_x000D_
.focus {_x000D_
z-index: 2;_x000D_
}
_x000D_
<html ng-app="showcase">_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body class="container">_x000D_
<label class="control-label">Person</label>_x000D_
<div class="input-merge" ng-controller="Ctrl as showCase">_x000D_
<div class="col-xs-4">_x000D_
<input class="form-control input-sm" name="initials" type="text" id="initials"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="person.initials" placeholder="Initials" />_x000D_
</div>_x000D_
_x000D_
<div class="col-xs-2">_x000D_
<input class="form-control input-sm" name="prefixes" type="text" id="prefixes"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="persoon.prefixes" placeholder="Prefixes" />_x000D_
</div>_x000D_
_x000D_
<div class="col-xs-6">_x000D_
<input class="form-control input-sm" name="surname" type="text" id="surname"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="persoon.surname" placeholder="Surname" />_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
With this it is possible to set the width of the individual inputs to your liking. Also a minor issue with the above snippets was that the input looks incomplete when focussed or when it is not valid. I fixed this with some angular code, but you can just as easily do this with jQuery or native javascript or whatever.
The code adds the class .focus to the containing div's, so it can get a higher z-index then the others when the input is focussed.
For Android .so
files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf
, objdump
and nm
.
if you are using target sdk as 23 add below code in your build.gradle
android{
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary 'org.apache.http.legacy'
}
and change your buildscript to
classpath 'com.android.tools.build:gradle:1.3.0'
for more info follow this link
You put the if
at the end:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension must start with at least one outer loop.
This method lets TextField to finish all processing (copy/paste/undo safe). Does not require to extend classes and allows you to decide what to do with new text after every change (to push it to logic, or turn back to previous value, or even to modify it).
// fired by every text property change
textField.textProperty().addListener(
(observable, oldValue, newValue) -> {
// Your validation rules, anything you like
// (! note 1 !) make sure that empty string (newValue.equals(""))
// or initial text is always valid
// to prevent inifinity cycle
// do whatever you want with newValue
// If newValue is not valid for your rules
((StringProperty)observable).setValue(oldValue);
// (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
// to anything in your code. TextProperty implementation
// of StringProperty in TextFieldControl
// will throw RuntimeException in this case on setValue(string) call.
// Or catch and handle this exception.
// If you want to change something in text
// When it is valid for you with some changes that can be automated.
// For example change it to upper case
((StringProperty)observable).setValue(newValue.toUpperCase());
}
);
For your case just add this logic inside. Works perfectly.
if (newValue.equals("")) return;
try {
Integer i = Integer.valueOf(newValue);
// do what you want with this i
} catch (Exception e) {
((StringProperty)observable).setValue(oldValue);
}
I know of two ways to do it.
Method 1
The first method (which I prefer) is to use msbuild:
msbuild project.sln /Flags...
Method 2
You can also run:
vcexpress project.sln /build /Flags...
The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.
Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).
So, the end result might be:
os.system("msbuild project.sln /p:Configuration=Debug")
You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).
A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
such as get my_list[x] in templates:
in template
{% load index %}
{{ my_list|index:x }}
templatetags/index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]
if my_list = [['a','b','c'], ['d','e','f']]
, you can use {{ my_list|index:x|index:y }}
in template to get my_list[x][y]
It works fine with "for"
{{ my_list|index:forloop.counter0 }}
Tested and works well ^_^
JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.
JavaScript will not be able to determine your Windows user name.
A new way to do this using swift. The UIWebView is no more and WKWebView is the new class to load web pages, which ensures the Safari features to the web view.
import WebKit
let preferences = WKPreferences()
preferences.javaScriptCanOpenWindowsAutomatically = false
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let webView = WKWebView(frame: self.view.bounds, configuration: configuration)
let request = NSURLRequest(URL: NSURL(string: "http://nshipster.com"))
webView.loadRequest(request)
If j
is equal to sqrt(i)
it might also be a valid factor, not only if it's smaller.
To iterate up to and including sqrt(i)
in your inner loop, you could write:
for (int j=2; j*j<=i; j++)
(Compared to using sqrt(i)
this has the advantage to not need conversion to floating point numbers.)
put the event handler function inside $(document).ready(function(){...}). it shall work now
also add preventDefault() to restrict page refreshing
$(document).ready(function() {
$("#postcontent").submit(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
url : "add_new_post.php",
data : $("#postcontent").serialize(),
beforeSend : function() {
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},
success : function(response) {
alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
e.preventDefault();
});
});
Because python 3 print() function allows end="" definition, that satisfies the majority of issues.
In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:
from pprint import PrettyPrinter
class CommaEndingPrettyPrinter(PrettyPrinter):
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
# this is where to tell it what you want instead of the default "\n"
self._stream.write(",\n")
def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
printer = CommaEndingPrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
Now, when I do:
comma_ending_prettyprint(row, stream=outfile)
I get what I wanted (substitute what you want -- Your Mileage May Vary)
ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).
While they aren't finalised however, they can usually be found online, as drafts. Most of the times the final version doesn't differ significantly from the last draft, so while not perfect, they'll suit just fine.
Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)
No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.
Maybe placing the jquery.ui.widget.js
as second after jquery.ui.core.js
.
You can also simply use this:
.bg_rgba {
background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), url('https://picsum.photos/200');
width: 200px;
height: 200px;
border: 1px solid black;
}
_x000D_
<div class='bg_rgba'></div>
_x000D_
You can change the opacity of the color to your preference.
Thanks for @bkurzius's answer and this update is for Charles 3.10+. (The reason is here)
Install Charles Root Certificate on a Mobile Device or Remote Browser...
, and just follow the instruction. (use the Android's browser to download and install the certificate.)The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.
No, you can't use a non-standard size or dimension, as it'd wreak havoc on peoples' browsers wherever the icons are displayed. You could make it 12x16 (with four pixels of white/transparent padding on the 12 pixel side) to preserve your aspect ratio, but you can't go bigger (well, you can, but the browser'll shrink it).
JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];_x000D_
_x000D_
myArr.forEach(function(elem){_x000D_
if (elem === 3) {_x000D_
return;_x000D_
}_x000D_
_x000D_
console.log(elem);_x000D_
});
_x000D_
Output: 1, 2, 4
I suggest you check out chunked
and disk.frame
. They both have functions for reading in CSVs chunk-by-chunk.
In particular, disk.frame::csv_to_disk.frame
may be the function you are after?
I'd go for jpeg
. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick
Hope this helps
You can include lambda along with map:
list(map(lambda a: a+2, [1, 2, 3]))
I came across another solution to use the Google play services on an emulator. The guys at http://www.genymotion.com/ provide very fast emulators on which you can install Google play services. They just need you to sign up to begin downloading and you need Virtual box installed. At the moment they cater for Android 16 and 17 but more are on the way.
if string is a variable, use the .repr method on it:
>>> s = '\tgherkin\n'
>>> s
'\tgherkin\n'
>>> print(s)
gherkin
>>> print(s.__repr__())
'\tgherkin\n'
One more:
def month_converter(month):
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
return months.index(month) + 1
Fixing the seed is essential when we try to optimize a function that involves randomly generated numbers (e.g. in simulation based estimation). Loosely speaking, if we do not fix the seed, the variation due to drawing different random numbers will likely cause the optimization algorithm to fail.
Suppose that, for some reason, you want to estimate the standard deviation (sd) of a mean-zero normal distribution by simulation, given a sample. This can be achieved by running a numerical optimization around steps
The following functions do this, once without step 1., once including it:
# without fixing the seed
simllh <- function(sd, y, Ns){
simdist <- density(rnorm(Ns, mean = 0, sd = sd))
llh <- sapply(y, function(x){ simdist$y[which.min((x - simdist$x)^2)] })
return(-sum(log(llh)))
}
# same function with fixed seed
simllh.fix.seed <- function(sd,y,Ns){
set.seed(48)
simdist <- density(rnorm(Ns,mean=0,sd=sd))
llh <- sapply(y,function(x){simdist$y[which.min((x-simdist$x)^2)]})
return(-sum(log(llh)))
}
We can check the relative performance of the two functions in discovering the true parameter value with a short Monte Carlo study:
N <- 20; sd <- 2 # features of simulated data
est1 <- rep(NA,1000); est2 <- rep(NA,1000) # initialize the estimate stores
for (i in 1:1000) {
as.numeric(Sys.time())-> t; set.seed((t - floor(t)) * 1e8 -> seed) # set the seed to random seed
y <- rnorm(N, sd = sd) # generate the data
est1[i] <- optim(1, simllh, y = y, Ns = 1000, lower = 0.01)$par
est2[i] <- optim(1, simllh.fix.seed, y = y, Ns = 1000, lower = 0.01)$par
}
hist(est1)
hist(est2)
The resulting distributions of the parameter estimates are:
When we fix the seed, the numerical search ends up close to the true parameter value of 2 far more often.
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html
I ran into a similar problem using the maven-shade-plugin. I found the solution to my problems in their example page above.
You can
Best practice would be #4 if you are using non-modal forms.
Simply:
// Default export (recommended)
export {default} from './MyClass'
// Default export with alias
export {default as d1} from './MyClass'
// In >ES7, it could be
export * from './MyClass'
// In >ES7, with alias
export * as d1 from './MyClass'
Or by functions names :
// export by function names
export { funcName1, funcName2, …} from './MyClass'
// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'
More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).
The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).
Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.
In python 3.8+ you can do :
(a:=a+1) #same as ++a (increment, then return new value)
(a:=a+1)-1 #same as a++ (return the incremented value -1) (useless)
You can do a lot of thinks with this.
>>> a = 0
>>> while (a:=a+1) < 5:
print(a)
1
2
3
4
Or if you want write somthing with more sophisticated syntaxe (the goal is not optimization):
>>> del a
>>> while (a := (a if 'a' in locals() else 0) + 1) < 5:
print(a)
1
2
3
4
It will return 0 even if 'a' doesn't exist without errors, and then will set it to 1
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC
Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");
If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:
Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or = (Color) ColorConverter.ConvertFromString("#FFCC66") ;
Its quite easy on computer a you don't need to do anything just make sure both system are on same network if its not internet access(for this you need static ip). Okay now on computer b go to start menu find configuration under oracle folder click Net Configuration Assistant under that folder when window pop up click Local net configuration option it must be third option.
Now click add and click next in next screen it will ask service name here you need to add oracle global database name of computer A(Normally I use oracle86 for my installation) now click next next screen choose protocol normally its tcp click next in host name enter computer A's name you can found that in my computer properties. Click next don't change port untill you have changed that in Computer A click next and choose test connection now here you can check your connection working or not if the error is username and password not correct then click login credential button and fill correct username and password. If its saying unable to reach computer ot target not found than you must add exception in firewall for 1521 port or just disable firewall on computer A.
figure (1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig, 'Position', [0 0 xwidth ywidth])
plot(x,y)
print -depsc2 correlation.eps; % for saving in eps, look up options for saving as png or other formats you may need
This saves the figure in the dimensions specified
You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.
If you use multiple users at android, verify that the app is uninstalled everywhere.
On my PC I had to open the Tomcat6 entry again after the 7th step mentioned above and then change the default option under Server locations
to Use tomcat installation
.
O.k. this is going to sound pretty absurd, but humor me.
For me the problem got resolved when I changed my statement to this :
SELECT * FROM `table`
I made two changes
1.) Made the table name lower case - I know !!
2.) Used the specific quote symbol = ` : It's the key above your TAB
The solution does sound absurd, but it worked and it's Saturday evening and I've been working since 9 a.m. - So I'll take it :)
Good luck.
The Set statement is only used for object variables (like Range
, Cell
or Worksheet
in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer
. You can find a good explanation for when to use set here.
The other problem is, that your variable g1val
isn't actually declared as Integer
, but has the type Variant
. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant
. You can only shorten your Dim statement this way:
Dim intColumn As Integer, intRow As Integer 'This creates two integers
For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.
Try this example to understand the difference:
Sub Dimming()
Dim thisBecomesVariant, thisIsAnInteger As Integer
Dim integerOne As Integer, integerTwo As Integer
MsgBox TypeName(thisBecomesVariant) 'Will display "Empty"
MsgBox TypeName(thisIsAnInteger ) 'Will display "Integer"
MsgBox TypeName(integerOne ) 'Will display "Integer"
MsgBox TypeName(integerTwo ) 'Will display "Integer"
'By assigning an Integer value to a Variant it becomes Integer, too
thisBecomesVariant = 0
MsgBox TypeName(thisBecomesVariant) 'Will display "Integer"
End Sub
Two further notices on your code:
First remark: Instead of writing
'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
g1val = g1val 'Don't change g1val
Else
g1val = Cells(33, i).Value 'Otherwise set g1val to the cell's value
End If
you could simply write
'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
g1val = Cells(33, i).Value 'Set g1val to the cell's value
End If
Since you don't want to change g1val
in the other case.
Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.
What about that:
<div style="min-height: 100vh;">
content
</div>
<footer>
copyright blah blah
</footer>
/**
* Created by Ilya Gazman on 3/6/2016.
*/
public class ImageSaver {
private String directoryName = "images";
private String fileName = "image.png";
private Context context;
private boolean external;
public ImageSaver(Context context) {
this.context = context;
}
public ImageSaver setFileName(String fileName) {
this.fileName = fileName;
return this;
}
public ImageSaver setExternal(boolean external) {
this.external = external;
return this;
}
public ImageSaver setDirectoryName(String directoryName) {
this.directoryName = directoryName;
return this;
}
public void save(Bitmap bitmapImage) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(createFile());
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@NonNull
private File createFile() {
File directory;
if(external){
directory = getAlbumStorageDir(directoryName);
}
else {
directory = context.getDir(directoryName, Context.MODE_PRIVATE);
}
if(!directory.exists() && !directory.mkdirs()){
Log.e("ImageSaver","Error creating directory " + directory);
}
return new File(directory, fileName);
}
private File getAlbumStorageDir(String albumName) {
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
}
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
public Bitmap load() {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(createFile());
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
To save:
new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
save(bitmap);
To load:
Bitmap bitmap = new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
load();
Edit:
Added ImageSaver.setExternal(boolean)
to support saving to external storage based on googles example.
You do not need to do anything special to start. Start with a normal java project, either maven or gradle or IDE project layout with starter dependency.
You need just one main class, as per guide here and rest...
There is no constrained package structure. Actual structure will be driven by your requirement/whim and the directory structure is laid by build-tool / IDE
You can follow same structure that you might be following for a Spring MVC application.
You can follow either way
A project is divided into layers:
for example: DDD style
or
any layer structure suitable to your problem for which you are writing problem.
A project divided into modules or functionalities or features and A module is divided into layers like above
I prefer the second, because it follows Business context. Think in terms of concepts.
What you do is dependent upon how you see the project. It is your code organization skills.
Looked around online too long not to contribute. After trying to type in the mysql prompt from the command line, I was continuing to receive this message:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
This was due to the fact that my local mysql server was no longer running. In order to restart the server, I navigated to
shell> cd /user/local/bin
where my mysql.server was located. From here, simply type:
shell> mysql.server start
This will relaunch the local mysql server.
From there you can reset the root password if need be..
mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
-> WHERE User='root';
mysql> FLUSH PRIVILEGES;
Not sure if this answer the question or going to help....
$dt = '6/26/1970' ; // or // '6.26.1970' ;
$dt = preg_replace("([.]+)", "/", $dt);
$test_arr = explode('/', $dt);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))
{ echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }
else
{ echo "no good...format must be in mm/dd/yyyy"; }
Quick example:
On Ubuntu, if you are interested, for instance, in Gmail then open the Terminal and type:
nslookup -q=mx gmail.com
I recommend web storage. Example:
// Storing the data:
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
Just replace variable
with your variable name and text
with what you want to store. According to W3Schools, it's better than cookies.
Have you tried DevDefined.OAuth?
I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.
It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:
1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder
extensibility.
2) Build the library and reference it in your Web API project.
3) Create a custom context builder to support building a context from HttpRequestMessage
:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;
using DevDefined.OAuth.Framework;
public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
public WebApiOAuthContextBuilder()
: base(UriAdjuster)
{
}
public IOAuthContext FromHttpRequest(HttpRequestMessage request)
{
var context = new OAuthContext
{
RawUri = this.CleanUri(request.RequestUri),
Cookies = this.CollectCookies(request),
Headers = ExtractHeaders(request),
RequestMethod = request.Method.ToString(),
QueryParameters = request.GetQueryNameValuePairs()
.ToNameValueCollection(),
};
if (request.Content != null)
{
var contentResult = request.Content.ReadAsByteArrayAsync();
context.RawContent = contentResult.Result;
try
{
// the following line can result in a NullReferenceException
var contentType =
request.Content.Headers.ContentType.MediaType;
context.RawContentType = contentType;
if (contentType.ToLower()
.Contains("application/x-www-form-urlencoded"))
{
var stringContentResult = request.Content
.ReadAsStringAsync();
context.FormEncodedParameters =
HttpUtility.ParseQueryString(stringContentResult.Result);
}
}
catch (NullReferenceException)
{
}
}
this.ParseAuthorizationHeader(context.Headers, context);
return context;
}
protected static NameValueCollection ExtractHeaders(
HttpRequestMessage request)
{
var result = new NameValueCollection();
foreach (var header in request.Headers)
{
var values = header.Value.ToArray();
var value = string.Empty;
if (values.Length > 0)
{
value = values[0];
}
result.Add(header.Key, value);
}
return result;
}
protected NameValueCollection CollectCookies(
HttpRequestMessage request)
{
IEnumerable<string> values;
if (!request.Headers.TryGetValues("Set-Cookie", out values))
{
return new NameValueCollection();
}
var header = values.FirstOrDefault();
return this.CollectCookiesFromHeaderString(header);
}
/// <summary>
/// Adjust the URI to match the RFC specification (no query string!!).
/// </summary>
/// <param name="uri">
/// The original URI.
/// </param>
/// <returns>
/// The adjusted URI.
/// </returns>
private static Uri UriAdjuster(Uri uri)
{
return
new Uri(
string.Format(
"{0}://{1}{2}{3}",
uri.Scheme,
uri.Host,
uri.IsDefaultPort ?
string.Empty :
string.Format(":{0}", uri.Port),
uri.AbsolutePath));
}
}
4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute
attribute:
public override void OnAuthorization(HttpActionContext actionContext)
{
// the only change I made is use the custom context builder from step 3:
OAuthContext context =
new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);
try
{
provider.AccessProtectedResourceRequest(context);
// do nothing here
}
catch (OAuthException authEx)
{
// the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
// implementation is overloaded to return a problem report string as per
// the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
};
}
}
I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder
which I'm using in my provider) but it should work fine.
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...