One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
Here a little bit more optimized regexp:
(?:(?:(https?|ftp|file):\/\/|www\.|ftp\.)|([\w\-_]+(?:\.|\s*\[dot\]\s*[A-Z\-_]+)+))([A-Z\-\.,@?^=%&:\/~\+#]*[A-Z\-\@?^=%&\/~\+#]){2,6}?
Here is test with data: https://regex101.com/r/sFzzpY/6
You can remove webdav module manually from GUI for the particular in IIS.
1) Goto the IIs.
2) Goto the respective site.
3) Open "Handler Mappings"
4) Scroll downn and select WebDav module. Right click on it and delete it.
Note: this will also update your web.config of the web app.
Since this is a vmdk file, you could use VMWare's vdiskmanager
, if it's available for your platform. VMWare has x86 Linux, Windows, and OS X versions here (see "Attachments" on the right rail).
And then you just do:
1023856-vdiskmanager-windows-7.0.1.exe -x 30720M Machine-disk1.vmdk
It avoids having to clone, then expand the disk. Now, the downside is you need the extra tool, and vmdk is VMWare's disk format, and you're still using Virtualbox, so there could be incompatibilities.
qemu-img
might also work, but I'm not sure if it supports resizing vmdk files. It would look something like:
qemu-img resize Machine-disk1.vmdk +8G
And just a reminder, with both, you still have to grow the partition after resizing the underlying disk. All these tools are essentially dd if=/dev/old_disk of=/dev/new_disk bs=16M
.
The maximum value of an integer (which is signed) is 2147483647
. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.
If that exception wouldn't be thrown, you'd have a value of -2145629296
for your Volume
, which is most probably not wanted.
Solution: Use an Int64
for your volume. With a max value of 9223372036854775807
, you're probably more on the safe side.
In Python, += is sugar coating for the __iadd__
special method, or __add__
or __radd__
if __iadd__
isn't present. The __iadd__
method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.
Here's a simple custom class that implements the __iadd__
special method. You initialize the object with an int, then can use the += operator to add a number. I've added a print statement in __iadd__
to show that it gets called. Also, __iadd__
is expected to return an object, so I returned the addition of itself plus the other number which makes sense in this case.
>>> class Adder(object):
def __init__(self, num=0):
self.num = num
def __iadd__(self, other):
print 'in __iadd__', other
self.num = self.num + other
return self.num
>>> a = Adder(2)
>>> a += 3
in __iadd__ 3
>>> a
5
Hope this helps.
You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.
All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.
It looks something like this:
NUM_PROCS=$(ps -e | sed 1d | wc -l)
I hope that helps add some handy information to this discussion.
I use a VBScript file for doing this on Windows platform, it servers me very well.
set shell = CreateObject("WScript.Shell")
shell.run"rsync -a [email protected]:/Users/Name/Projects/test ."
WScript.Sleep 100
shell.SendKeys"Your_Password"
shell.SendKeys "{ENTER}"
use
npm config set registry http://registry.npmjs.org/
so that npm requests for http
url instead of https
.
and then try the same npm install
command
Why not use a combination of the CSS and backend? Use:
style='text-transform:uppercase'
on the TextBox, and in your codebehind use:
Textbox.Value.ToUpper();
You can also easily change your regex on the validator to use lowercase and uppercase letters. That's probably the easier solution than forcing uppercase on them.
Let's say you have defined an empty array:
$myArr = array();
If you want to simply add an element, e.g. 'New Element to Array', write
$myArr[] = 'New Element to Array';
if you are calling the data from the database, below code will work fine
$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
while($result = mysql_fetch_object($query))
{
//adding data to the array
$myArr[] = $result->$element;
}
}
Maybe you can try creating the unexisting columns and calling union
(unionAll
for Spark 1.6 or lower):
cols = ['id', 'uniform', 'normal', 'normal_2']
df_1_new = df_1.withColumn("normal_2", lit(None)).select(cols)
df_2_new = df_2.withColumn("normal", lit(None)).select(cols)
result = df_1_new.union(df_2_new)
The issue is not with the version of node. Instead, it is the way NodeJS is installed by default in Ubuntu. When running a Node application in Ubuntu you have to run nodejs somethign.js
instead of node something.js
So the application name called in the terminal is nodejs
and not node
. This is why there is a need for a symlink to simply forward all the commands received as node
to nodejs
.
sudo ln -s /usr/bin/nodejs /usr/bin/node
.any()
and .all()
are great for the extreme cases, but not when you're looking for a specific number of null values. Here's an extremely simple way to do what I believe you're asking. It's pretty verbose, but functional.
import pandas as pd
import numpy as np
# Some test data frame
df = pd.DataFrame({'num_legs': [2, 4, np.nan, 0, np.nan],
'num_wings': [2, 0, np.nan, 0, 9],
'num_specimen_seen': [10, np.nan, 1, 8, np.nan]})
# Helper : Gets NaNs for some row
def row_nan_sums(df):
sums = []
for row in df.values:
sum = 0
for el in row:
if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
sum+=1
sums.append(sum)
return sums
# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
sums = row_nan_sums(df)
indices = []
i = 0
for sum in sums:
if (sum >= k):
indices.append(i)
i += 1
return indices
# test
print(df)
print(query_k_plus_sums(df, 2))
Output
num_legs num_wings num_specimen_seen
0 2.0 2.0 10.0
1 4.0 0.0 NaN
2 NaN NaN 1.0
3 0.0 0.0 8.0
4 NaN 9.0 NaN
[2, 4]
Then, if you're like me and want to clear those rows out, you just write this:
# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)
Output:
num_legs num_wings num_specimen_seen
0 4.0 0.0 NaN
1 0.0 0.0 8.0
2 2.0 2.0 10.0
I didn't want to upgrade react-scripts
, so I used the 3rd party reinstall npm module to reinstall it, and it worked.
npm i -g npm-reinstall
reinstall react-scripts
Try this,
Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText();
From Spark 2.3(SPARK-22771) Spark SQL supports the concatenation operator ||
.
For example;
val df = spark.sql("select _c1 || _c2 as concat_column from <table_name>")
It is used to influence sorting in the CSS cascade when sorting by origin is done. It has nothing to do with specificity like stated here in other answers.
Here is the priority from lowest to highest:
After that specificity takes place for the rules still having a finger in the pie.
References:
I had the same problem. But just restarting my computer after setting up the Maven path resolved the issue.
Variable Name: M2_Home Variable Value:C:\Apache\apache-maven-3.3.9
Variable Name: Path Variable Value:C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%JAVA_HOME%\bin\;%M2_HOME%\bin\
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.
While these are all viable answers, I decided to give my way of checking if local repo is in line with the remote, whithout fetching or pulling. In order to see where my branches are I use simply:
git remote show origin
What it does is return all the current tracked branches and most importantly - the info whether they are up to date, ahead or behind the remote origin ones. After the above command, this is an example of what is returned:
* remote origin
Fetch URL: https://github.com/xxxx/xxxx.git
Push URL: https://github.com/xxxx/xxxx.git
HEAD branch: master
Remote branches:
master tracked
no-payments tracked
Local branches configured for 'git pull':
master merges with remote master
no-payments merges with remote no-payments
Local refs configured for 'git push':
master pushes to master (local out of date)
no-payments pushes to no-payments (local out of date)
Hope this helps someone.
Imagine you've thread A and thread B. They are both synchronised
on the same object and inside this block there's a global variable they are both updating;
static boolean commonVar = false;
Object lock = new Object;
...
void threadAMethod(){
...
while(commonVar == false){
synchornized(lock){
...
commonVar = true
}
}
}
void threadBMethod(){
...
while(commonVar == true){
synchornized(lock){
...
commonVar = false
}
}
}
So, when thread A enters in the while
loop and holds the lock, it does what it has to do and set the commonVar
to true
. Then thread B comes in, enters in the while
loop and since commonVar
is true
now, it is be able to hold the lock. It does so, executes the synchronised
block, and sets commonVar
back to false
. Now, thread A again gets it's new CPU window, it was about to quit the while
loop but thread B has just set it back to false
, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.
It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised
block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.
CoreUtils referred to in other posts does NOT show the real implementation of most of the functionality which I think you seek. In most cases it provides front-ends for the actual functions that retrieve the data, which can be found here:
It is build upon Gnulib with the actual source code in the lib-subdirectory
If you want an ANSI SQL-92 version:
select view_definition from information_schema.views where table_name = 'view_name';
func mimeTypeForPath(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
PDF Hummus. see for http://pdfhummus.com/ - contains all required features for manipulation with PDF files except rendering.
In SSMS:
Now, this will drop everything, including the database. Make sure to remove the code for the items you don't want dropped. Alternatively, in the "Choose Objects" section, instead of selecting to script entire database just select the items you want to remove.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
i don't use ssl authentication and this jackson-databind contain jackson-core.jar and jackson-databind.jar, and then change the RequestMapping content like this:
@RequestMapping(value = "/id/{number}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
public @ResponseBody Customer findCustomer(@PathVariable int number){
Customer result = customerService.findById(number);
return result;
}
attention: if your produces is not "application/json" type and i had not noticed this and got an 406 error, help this can help you out.
I believe that the problem is that the WebRequest
measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager
will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit
which by default gets the value from ServicePointManager.DefaultConnectionLimit
. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.
I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint
limitation.
Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest
does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.
And yes, you must code your app around the WebRequest.BeginGetRequestStream
(for POST
s with content) and WebRequest.BeginGetResponse
(for GET
s and POSTS
s). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint
issue is orthogonal to this: the queueing behavior happens with async calls too.
ConcurrentLinkedQueue
uses a lock-free queue (based off the newer CAS instruction).
You can try out baboonstack, which includes redis and also a node.js and mongoDB version manager. And it's cross platform.
I have tried all the solutions above, but the following solved my problem
chcon -R -t httpd_sys_rw_content_t your_file_directory
echo
Not having return type
print
Have return type
print_r()
Outputs as formatted,
This is the best .htaccess
I have used in my actual website:
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
##Tweaks##
Header set X-Frame-Options SAMEORIGIN
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_headers.c>
Header set Connection keep-alive
<filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
Header set Cache-Control "max-age=2592000, public"
</filesmatch>
<filesmatch "\.(jpg|jpeg|png)$">
Header set Cache-Control "max-age=1209600, public"
</filesmatch>
# css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
<filesmatch "\.(css)$">
Header set Cache-Control "max-age=31536000, private"
</filesmatch>
<filesmatch "\.(js)$">
Header set Cache-Control "max-age=1209600, private"
</filesmatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</filesMatch>
</IfModule>
I had a similar problem and found your answer.. I eventually came to a solution.
It looks like the source of Chart.js has the following(presumably because it is not supposed to re-render and entirely different graph in the same canvas):
//High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
if (window.devicePixelRatio) {
context.canvas.style.width = width + "px";
context.canvas.style.height = height + "px";
context.canvas.height = height * window.devicePixelRatio;
context.canvas.width = width * window.devicePixelRatio;
context.scale(window.devicePixelRatio, window.devicePixelRatio);
}
This is fine if it is called once, but when you redraw multiple times you end up changing the size of the canvas DOM element multiple times causing re-size.
Hope that helps!
Very close! In your select
expression, you have to use a pipe (|
) before contains
.
This filter produces the expected output.
. - map(select(.Names[] | contains ("data"))) | .[] .Id
The jq Cookbook has an example of the syntax.
Filter objects based on the contents of a key
E.g., I only want objects whose genre key contains "house".
$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]' $ echo "$json" | jq -c '.[] | select(.genre | contains("house"))' {"genre":"deep house"} {"genre":"progressive house"}
Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.
The simplest way is to wrap the whole expression in an array constructor:
$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]
You can also use the map function:
$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]
map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f)
is equivalent to [.[]|f]
.
In gradle, after copying all files folders to libs/
jniLibs.srcDirs = ['libs']
Adding the above line to sourceSets
in build.gradle
file worked. Nothing else worked whatsoever.
You can also use the join command (dplyr).
For example:
new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
If you have a valid integer value and your requirement is to compare values, you can simply go ahead with the comparison as seen below.
Sub t()
Dim i As Integer
Dim s As String
' pass
i = 65
s = "65"
If i = s Then
MsgBox i
End If
' fail - Type Mismatch
i = 65
s = "A"
If i = s Then
MsgBox i
End If
End Sub
A persistence context handles a set of entities which hold data to be persisted in some persistence store (e.g. a database). In particular, the context is aware of the different states an entity can have (e.g. managed, detached) in relation to both the context and the underlying persistence store.
Although Hibernate-related (a JPA provider), I think these links are useful:
http://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch03.html
http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/architecture.html
In Java EE, a persistence context is normally accessed via an EntityManager.
http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html
The various states an entity can have and the transitions between these are described below:
http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/objectstate.html
http://gerrydevstory.com/wp-content/uploads/2012/05/jpa-state-transtition.png
You can't. Flexbox is not a grid system. It does not have the language constructs to do what you're asking for, at least not if you're using justify-content: space-between
. The closest you can get with Flexbox is to use the column orientation, which requires setting an explicit height:
http://cssdeck.com/labs/pvsn6t4z (note: prefixes not included)
ul {
display: flex;
flex-flow: column wrap;
align-content: space-between;
height: 4em;
}
However, it would be simpler to just use columns, which has better support and doesn't require setting a specific height:
http://cssdeck.com/labs/dwq3x6vr (note: prefixes not included)
ul {
columns: 15em;
}
You should add & make your BOT as administrator of the PRIVATE channel, otherwise chat not found
error happens.
If you have Git
installed on windows you can use the GNU Bash
.... it's built in.
https://superuser.com/questions/134685/run-curl-commands-from-windows-console/#483964
foreach
can handle arrays and objects. You can check this with:
$can_foreach = is_array($var) || is_object($var);
if ($can_foreach) {
foreach ($var as ...
}
You don't need to specifically check for Traversable
as others have hinted it in their answers, because all objects - like all arrays - are traversable in PHP.
More technically:
foreach
works with all kinds of traversables, i.e. with arrays, with plain objects (where the accessible properties are traversed) andTraversable
objects (or rather objects that define the internalget_iterator
handler).
(source)
Simply said in common PHP programming, whenever a variable is
and is not
you can use foreach
on it.
when you are using dependencies so your methods increased! google has a solution for that. that called Multidex!
NOTE: be sure that min SDK is over 14.
in your build.gradle :
android {
defaultConfig {
...
minSdkVersion 15
targetSdkVersion 28
multiDexEnabled true
}
...
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
FOR androidX USE :
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'
For more information please go to the orginal link :
What you ask for is the join operation.
With the how
argument, you can define how unique indices are handled.
Here, some article, which looks helpful concerning this point.
In the example below, I left out cosmetics (like renaming columns) for simplicity.
Code
import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )
df3 = df1.join(df2, how='outer', lsuffix='_df1', rsuffix='_df2')
print(df3)
Output
a_df1 b_df1 c_df1 a_df2 b_df2 c_df2
2014-01-01 NaN NaN NaN 0.109898 1.107033 -1.045376
2014-01-02 0.573754 0.169476 -0.580504 -0.664921 -0.364891 -1.215334
2014-01-03 -0.766361 -0.739894 -1.096252 0.962381 -0.860382 -0.703269
2014-01-04 0.083959 -0.123795 -1.405974 1.825832 -0.580343 0.923202
2014-01-05 1.019080 -0.086650 0.126950 -0.021402 -1.686640 0.870779
2014-01-06 -1.036227 -1.103963 -0.821523 -0.943848 -0.905348 0.430739
2014-01-07 NaN NaN NaN 0.312005 0.586585 1.531492
2014-01-08 NaN NaN NaN -0.077951 -1.189960 0.995123
It's actually pretty simple.
Just visit the following in your browser and use wrong credentials: http://username:[email protected]
That should "log you out".
This is not really related but if I was to asynchronously call a method e.g. matches(), I would use:
private final static ExecutorService service = Executors.newFixedThreadPool(10);
public static Future<Boolean> matches(final String x, final String y) {
return service.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return x.matches(y);
}
});
}
Then to call the asynchronous method I would use:
String x = "somethingelse";
try {
System.out.println("Matches: "+matches(x, "something").get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
I have tested this and it works. Just thought it may help others if they just came for the "asynchronous method".
class Graph<E> {
private List<Vertex<E>> vertices;
private static class Vertex<E> {
E elem;
List<Vertex<E>> neighbors;
}
}
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
i made my own utils. it is handy. :)
package samples.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* SpringMVC????
*
* @author ??([email protected])
*
*/
public final class WebContextHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);
private static WebContextHolder INSTANCE = new WebContextHolder();
public WebContextHolder get() {
return INSTANCE;
}
private WebContextHolder() {
super();
}
// --------------------------------------------------------------------------------------------------------------
public HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attributes.getRequest();
}
public HttpSession getSession() {
return getSession(true);
}
public HttpSession getSession(boolean create) {
return getRequest().getSession(create);
}
public String getSessionId() {
return getSession().getId();
}
public ServletContext getServletContext() {
return getSession().getServletContext(); // servlet2.3
}
public Locale getLocale() {
return RequestContextUtils.getLocale(getRequest());
}
public Theme getTheme() {
return RequestContextUtils.getTheme(getRequest());
}
public ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
public ApplicationEventPublisher getApplicationEventPublisher() {
return (ApplicationEventPublisher) getApplicationContext();
}
public LocaleResolver getLocaleResolver() {
return RequestContextUtils.getLocaleResolver(getRequest());
}
public ThemeResolver getThemeResolver() {
return RequestContextUtils.getThemeResolver(getRequest());
}
public ResourceLoader getResourceLoader() {
return (ResourceLoader) getApplicationContext();
}
public ResourcePatternResolver getResourcePatternResolver() {
return (ResourcePatternResolver) getApplicationContext();
}
public MessageSource getMessageSource() {
return (MessageSource) getApplicationContext();
}
public ConversionService getConversionService() {
return getBeanFromApplicationContext(ConversionService.class);
}
public DataSource getDataSource() {
return getBeanFromApplicationContext(DataSource.class);
}
public Collection<String> getActiveProfiles() {
return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
}
public ClassLoader getBeanClassLoader() {
return ClassUtils.getDefaultClassLoader();
}
private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
try {
return getApplicationContext().getBean(requiredType);
} catch (NoUniqueBeanDefinitionException e) {
LOGGER.error(e.getMessage(), e);
throw e;
} catch (NoSuchBeanDefinitionException e) {
LOGGER.warn(e.getMessage());
return null;
}
}
}
Use -D property=value rather than -D property = value (eliminate extra whitespaces). Thus -D mapred.reduce.tasks=value would work fine.
Setting number of map tasks doesnt always reflect the value you have set since it depends on split size and InputFormat used.
Setting the number of reduces will definitely override the number of reduces set on cluster/client-side configuration.
You could access your class's __dict__
attribute:
for i in range(3)
self.__dict__['group%d' % i]=self.getGroup(selected, header+i)
But why can't you just use an array named group
?
Try to use target size you need insted of TRUNCATEONLY in DBCC:
DBCC SHRINKFILE ('Wxlog0', 1)
And check this to articles:
http://msdn.microsoft.com/en-us/library/ms189493(SQL.90).aspx
http://support.microsoft.com/kb/907511
Edit:
You can try to move allocated pages to the beginning of the log file first with
DBCC SHRINKFILE ('Wxlog0', NOTRUNCATE)
and after that
DBCC SHRINKFILE ('Wxlog0', 1)
git bundle
I like that method, as it results in only one file, easier to copy around.
See ProGit: little bundle of joy.
See also "How can I email someone a git repository?", where the command
git bundle create /tmp/foo-all --all
is detailed:
git bundle
will only package references that are shown by git show-ref: this includes heads, tags, and remote heads.
It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file to contain objects already in the destination, as these are ignored when unpacking at the destination.
For using that bundle, you can clone it, specifying a non-existent folder (outside of any git repo):
git clone /tmp/foo-all newFolder
if you want to find about object name e.g. table name and stored procedure on which particular user has permission, use the following query:
SELECT pr.principal_id, pr.name, pr.type_desc,
pr.authentication_type_desc, pe.state_desc, pe.permission_name, OBJECT_NAME(major_id) objectName
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
--INNER JOIN sys.schemas AS s ON s.principal_id = sys.database_role_members.role_principal_id
where pr.name in ('youruser1','youruser2')
try
cat ~/.mysql_history
this will show you all mysql commands ran on the system
Also you can only set mediaPlayer.reset()
and in onDestroy
set it to release.
Convert ArrayList to JsonArray : Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]
This worked for me
PHP 7.2
AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
PHP 7.3
AddHandler application/x-httpd-ea-php73 .php
You can define an interface as array with simply extending the Array interface.
export interface MyInterface extends Array<MyType> { }
With this, any object which implements the MyInterface
will need to implement all function calls of arrays and only will be able to store objects with the MyType
type.
Or you can use what JQuery alreay made for you:
http://jqueryui.com/datepicker/#icon-trigger
It's what you are trying to achieve isn't it?
If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:
var arr = arr.OrderBy(x=>x).ToArray();
EDITED
You can look into sys.tables for checking existence desired table:
IF NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')
BEGIN
CREATE TABLE [SchemaName].[YourTable](
....
....
....
)
END
A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.
A procedure is executed using the CALL query.
ALTER TABLE TableName
DROP COLUMN Column1, Column2;
The syntax is
DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ]
ALTER TABLE TableName
DROP COLUMN Column1,
DROP COLUMN Column2;
or like this1:
ALTER TABLE TableName
DROP Column1,
DROP Column2;
1 The word COLUMN
is optional and can be omitted, except for RENAME COLUMN
(to distinguish a column-renaming operation from the RENAME
table-renaming operation). More info here.
In laravel 5.3, you should override the default showRegistrationForm()
by including the code below into the RegisterController.php
file in app\Http\Controllers\Auth
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
//return view('auth.register');
abort(404); //this will throw a page not found exception
}
since you don't want to allow registration, it's better to just throw 404 error
so the intruder knows he is lost. And when you are ready for registraation in your app, uncomment //return view('auth.register');
then comment abort(404);
\\\\\\\\\\\\\\\\\\\\JUST AN FYI///////////////////////////////
If you need to use multiple authentication like create auth for users, members, students, admin, etc. then i advise you checkout this hesto/multi-auth its an awesome package for unlimited auths in L5 apps.
You can read more abouth the Auth methodology and its associated file in this writeup.
Yes, you can use substitutions and check against the original string:
if not x%str1:bcd=%==x%str1% echo It contains bcd
The %str1:bcd=%
bit will replace a bcd
in str1
with an empty string, making it different from the original.
If the original didn't contain a bcd
string in it, the modified version will be identical.
Testing with the following script will show it in action:
@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal
And the results of various runs:
c:\testarea> testprog hello
c:\testarea> testprog abcdef
It contains bcd
c:\testarea> testprog bcd
It contains bcd
A couple of notes:
if
statement is the meat of this solution, everything else is support stuff.x
before the two sides of the equality is to ensure that the string bcd
works okay. It also protects against certain "improper" starting characters.1) File >>> Project Structure OR press Ctrl+Alt+Shift+S
2) In SDK Location Tab you will find SDK Location:
3) Change your Project SDK location to the one you have installed
4) Sync your project
How about
Select I.Fee
From Item I
WHERE (days(GETDATE()) - days(I.DateCreated) < 365)
INSERT INTO table
SELECT 'jonny', NULL
FROM dual -- Not Oracle? No need for dual, drop that line
WHERE NOT EXISTS (SELECT NULL -- canonical way, but you can select
-- anything as EXISTS only checks existence
FROM table
WHERE name = 'jonny'
)
This has been discussed in many posts but still I could not figure out a solution with:
android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"
Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:
Adapter class - getview():
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.my_ref_row, parent, false);
}
final Organization currentOrg = organizationlist.get(position).getOrganization();
TextView name = (TextView) view.findViewById(R.id.name);
Button btn = (Button) view.findViewById(R.id.btn_check);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
context.doSelection(currentOrg);
}
});
if(currentOrg.isSelected()){
btn.setBackgroundResource(R.drawable.sub_search_tick);
}else{
btn.setBackgroundResource(R.drawable.sub_search_tick_box);
}
}
In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):
public void doSelection(Organization currentOrg) {
Log.e("Btn clicked ", currentOrg.getOrgName());
if (currentOrg.isSelected() == false) {
currentOrg.setSelected(true);
} else {
currentOrg.setSelected(false);
}
adapter.notifyDataSetChanged();
}
You don't need to download and install shareware apps or tools. You can do it programitically from .NET using Assembly.GetReferencedAssemblies()
Assembly.LoadFile(@"app").GetReferencedAssemblies()
ORA-00907: missing right parenthesis
This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.
Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis
and leaves it to us to spot the actual bloomer.
The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.
Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.
In-line declaration doesn't have a comma and doesn't include the referencing column name.
CREATE TABLE historys_T (
history_record VARCHAR2 (8),
customer_id VARCHAR2 (8)
CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
order_id VARCHAR2 (10) NOT NULL,
CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)
Table level constraints are a separate component, and so do have a comma and do mention the referencing column.
CREATE TABLE historys_T (
history_record VARCHAR2 (8),
customer_id VARCHAR2 (8),
order_id VARCHAR2 (10) NOT NULL,
CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,
CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)
Here is a list of other syntax errors:
HISTORYS_T
before you have created the referenced ORDERS
table.LIBRARY_T
and FORMAT_T
). DATE DEFAULT sysdate
.Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).
As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.
HISTORY_T
has constraints called historys_T_FK
and fk_order_id_orders
, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk
. So history_customer_fk
and history_order_fk
respectively.LIBRARY_T
and FORMATS
. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.LIBRARY_T
is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.T_CUSTOMERS
is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers
is not a keyword.Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS
and LIBRARY_T
my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_
or a _TAB
.
For completeness, you can also use:
mystring = mystring.strip() # the while loop will leave a trailing space,
# so the trailing whitespace must be dealt with
# before or after the while loop
while ' ' in mystring:
mystring = mystring.replace(' ', ' ')
which will work quickly on strings with relatively few spaces (faster than re
in these situations).
In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).
In your example, using the default values of timeit.Timer.repeat(), I get the following times:
str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub: [3.741931446594549, 3.8389395858970374, 3.973777672860706]
split/join: [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]
EDIT:
Just came across this post which provides a rather long comparison of the speeds of these methods.
my start.sh file:
#/bin/bash
nohup forever -c php artisan your:command >>storage/logs/yourcommand.log 2>&1 &
There is one important thing only. FIRST COMMAND MUST BE "nohup", second command must be "forever" and "-c" parameter is forever's param, "2>&1 &" area is for "nohup". After running this line then you can logout from your terminal, relogin and run "forever restartall" voilaa... You can restart and you can be sure that if script halts then forever will restart it.
I <3 forever
When using Node.js, you can retrieve environment variables by key from the process.env
object:
for example
var mode = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'
Here is the answer that will explain setting environment variables in node.js
i've been researching for that too but unfortunately the facebook device auth is still on experimental and they didn't give new keys (partner) to use the device auth.
You can find the working example here: http://oauth-device-demo.appspot.com/ Just look at the website source and you can have the appID that works with it.
The other one is twitter PIN oauth it's working and publicly available (i'm using it) https://dev.twitter.com/docs/auth/pin-based-authorization
This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python
with open('words.txt') as fp:
contents = fp.read()
for entry in contents:
# do something with entry
According to the jQuery docs, calling toggle()
without parameters will toggle visibility.
$('#play-pause').click(function(){
$('#video-over').toggle();
});
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}
One obvious and straightforward possibility is to use "if-else conditions". In that example
x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)
** For the additional question in the edit** Is that what you expect ?
> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
>
> w <- ifelse((d1 == "e") & (d2 == "e"), 1,
+ ifelse((d1=="a") & (d2 == "b"), 2,
+ ifelse((d1 == "e"), 3, 99)))
>
> data.frame(d1, d2, w)
d1 d2 w
1 e e 1
2 c a 99
3 a b 2
If you do not feel comfortable with the ifelse
function, you can also work with the if
and else
statements for such applications.
The answer for Ashwini is great, in pointing out that scipy.math.factorial
, numpy.math.factorial
, math.factorial
are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial
is different. The one from scipy can take np.ndarray
as an input, while the others can't.
In [12]: import scipy.special
In [13]: temp = np.arange(10) # temp is an np.ndarray
In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)
TypeError: only length-1 arrays can be converted to Python scalars
In [15]: scipy.special.factorial(temp) # This works!
Out[15]:
array([ 1.00000000e+00, 1.00000000e+00, 2.00000000e+00,
6.00000000e+00, 2.40000000e+01, 1.20000000e+02,
7.20000000e+02, 5.04000000e+03, 4.03200000e+04,
3.62880000e+05])
So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
One more thing node provides is the ability to create multiple v8 instanes of node using node's child process( childProcess.fork() each requiring 10mb memory as per docs) on the fly, thus not affecting the main process running the server. So offloading a background job that requires huge server load becomes a child's play and we can easily kill them as and when needed.
I've been using node a lot and in most of the apps we build, require server connections at the same time thus a heavy network traffic. Frameworks like Express.js and the new Koajs (which removed callback hell) have made working on node even more easier.
SELECT *
FROM courses
WHERE DATE_ADD(NOW(), INTERVAL 2 HOUR) > start_time
See Date and Time Functions for other date/time manipulation.
I also wrote a small library which is specialized for the mapping of the json response into an object structure. I am internally using the library json-swift from David Owens. Maybe it is useful for someone else.
https://github.com/prine/ROJSONParser
Example Employees.json
{
"employees": [
{
"firstName": "John",
"lastName": "Doe",
"age": 26
},
{
"firstName": "Anna",
"lastName": "Smith",
"age": 30
},
{
"firstName": "Peter",
"lastName": "Jones",
"age": 45
}]
}
As next step you have to create your data model (EmplyoeeContainer and Employee).
Employee.swift
class Employee : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
var firstname:String {
return Value<String>.get(self, key: "firstName")
}
var lastname:String {
return Value<String>.get(self, key: "lastName")
}
var age:Int {
return Value<Int>.get(self, key: "age")
}
}
EmployeeContainer.swift
class EmployeeContainer : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
lazy var employees:[Employee] = {
return Value<[Employee]>.getArray(self, key: "employees") as [Employee]
}()
}
Then to actually map the objects from the JSON response you only have to pass the data into the EmployeeContainer class as param in the constructor. It does automatically create your data model.
var baseWebservice:BaseWebservice = BaseWebservice();
var urlToJSON = "http://prine.ch/employees.json"
var callbackJSON = {(status:Int, employeeContainer:EmployeeContainer) -> () in
for employee in employeeContainer.employees {
println("Firstname: \(employee.firstname) Lastname: \(employee.lastname) age: \(employee.age)")
}
}
baseWebservice.get(urlToJSON, callback:callbackJSON)
The console output looks then like the following:
Firstname: John Lastname: Doe age: 26
Firstname: Anna Lastname: Smith age: 30
Firstname: Peter Lastname: Jones age: 45
If you are drawing on the Graphics of the Control than you should do something draw on the Bitmap everything you are drawing on the canvas, but have in mind that Bitmap needs to be the exact size of the control you are drawing on:
Bitmap bmp = new Bitmap(myControl.ClientRectangle.Width,myControl.ClientRectangle.Height);
Graphics gBmp = Graphics.FromImage(bmp);
gBmp.DrawEverything(); //this is your code for drawing
gBmp.Dispose();
bmp.Save("image.png", ImageFormat.Png);
Or you can use a DrawToBitmap
method of the Control. Something like this:
Bitmap bmp = new Bitmap(myControl.ClientRectangle.Width, myControl.ClientRectangle.Height);
myControl.DrawToBitmap(bmp,new Rectangle(0,0,bmp.Width,bmp.Height));
bmp.Save("image.png", ImageFormat.Png);
I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:
import time
import operator
d = {"a"+str(i): i for i in range(1000000)}
def t1(dct):
mx = float("-inf")
key = None
for k,v in dct.items():
if v > mx:
mx = v
key = k
return key
def t2(dct):
v=list(dct.values())
k=list(dct.keys())
return k[v.index(max(v))]
def t3(dct):
return max(dct.items(),key=operator.itemgetter(1))[0]
start = time.time()
for i in range(25):
m = t1(d)
end = time.time()
print ("Iterating: "+str(end-start))
start = time.time()
for i in range(25):
m = t2(d)
end = time.time()
print ("List creating: "+str(end-start))
start = time.time()
for i in range(25):
m = t3(d)
end = time.time()
print ("Accepted answer: "+str(end-start))
results:
Iterating: 3.8201940059661865
List creating: 6.928712844848633
Accepted answer: 5.464320182800293
Windows Forms (and its visual designer) have been available for .NET Core (as a preview) since Visual Studio 2019 16.6. It's quite good, although sometimes I need to open Visual Studio 2019 16.7 Preview to get around annoying bugs.
See this blog post: Windows Forms Designer for .NET Core Released
Also, Windows Forms is now open source: https://github.com/dotnet/winforms
This article by Atul Gupta has sample code that covers several scenarios:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
{
$thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
}
}
closedir($handle);
}
A simple way to look at the extension using substr and strrpos
If you don't see the formatting option, you can do Tools->Import and Export settings to import the missing one.
Window>Preferences>Web>JSP files
linux
ffmpeg -i "/home/iorigins/????????????/123.mov" -f null /dev/null
ruby
result = `ffmpeg -i #{path} -f null - 2>&1`
r = result.match("frame=([0-9]+)")
p r[1]
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');_x000D_
let str = 'a1b2c.d3e';_x000D_
console.log(parseNum(str));
_x000D_
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
Here is the latest answer using a well optimized and nice csv plugin: (The code may not work on stackoverflow here but will work in your project as i have tested it myself)
Using jquery and jquery.csv library (Very well optimized and perfectly escapes everything) https://github.com/typeiii/jquery-csv
// Create an array of objects
const data = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }
];
// Convert to csv
const csv = $.csv.fromObjects(data);
// Download file as csv function
const downloadBlobAsFile = function(csv, filename){
var downloadLink = document.createElement("a");
var blob = new Blob([csv], { type: 'text/csv' });
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = filename;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
// Download csv file
downloadBlobAsFile(csv, 'filename.csv');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.tutorialjinni.com/jquery-csv/1.0.11/jquery.csv.min.js"></script>
_x000D_
I encountered the same problem... I solved it by creating a custom axios instance. and using that to make a authenticated delete request..
const token = localStorage.getItem('token');
const request = axios.create({
headers: {
Authorization: token
}
});
await request.delete('<your route>, { data: { <your data> }});
Using the following pipeline script:
pipeline {
agent { label "master" }
options { skipDefaultCheckout() }
stages {
stage('CleanWorkspace') {
steps {
cleanWs()
}
}
}
}
Follow these steps:
To use CurrentDb.Execute, your query must be an action query, AND in quotes.
CurrentDb.Execute "queryname"
if (listA.Except(listB).Any())
There's a lot of misunderstanding being displayed here. Unicode isn't an encoding, but the Unicode standard is devoted primarily to encoding anyway.
ISO 10646 is the international character set you (probably) care about. It defines a mapping between a set of named characters (e.g., "Latin Capital Letter A" or "Greek small letter alpha") and a set of code points (a number assigned to each -- for example, 61 hexadecimal and 3B1 hexadecimal for those two respectively; for Unicode code points, the standard notation would be U+0061 and U+03B1).
At one time, Unicode defined its own character set, more or less as a competitor to ISO 10646. That was a 16-bit character set, but it was not UTF-16; it was known as UCS-2. It included a rather controversial technique to try to keep the number of necessary characters to a minimum (Han Unification -- basically treating Chinese, Japanese and Korean characters that were quite a bit alike as being the same character).
Since then, the Unicode consortium has tacitly admitted that that wasn't going to work, and now concentrate primarily on ways to encode the ISO 10646 character set. The primary methods are UTF-8, UTF-16 and UCS-4 (aka UTF-32). Those (except for UTF-8) also have LE (little endian) and BE (big-endian) variants.
By itself, "Unicode" could refer to almost any of the above (though we can probably eliminate the others that it shows explicitly, such as UTF-8). Unqualified use of "Unicode" probably happens the most often on Windows, where it will almost certainly refer to UTF-16. Early versions of Windows NT adopted Unicode when UCS-2 was current. After UCS-2 was declared obsolete (around Win2k, if memory serves), they switched to UTF-16, which is the most similar to UCS-2 (in fact, it's identical for characters in the "basic multilingual plane", which covers a lot, including all the characters for most Western European languages).
The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.
Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.
in rare cases when you can't use strncat
, strcat
or strcpy
. And you don't have access to <string.h>
so you can't use strlen
. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..
char *combineStrings(char* inputA, char* inputB) {
size_t len = 0, lenB = 0;
while(inputA[len] != '\0') len++;
while(inputB[lenB] != '\0') lenB++;
char* output = malloc(len+lenB);
sprintf((char*)output,"%s%s",inputA,inputB);
return output;
}
It just needs #include <stdio.h>
which you will have most likely included already
Simplest solution I have seen
var offset = $("#target-element").offset();
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
}, 1000);
df = df.assign(New_ID=[880 + i for i in xrange(len(df))])[['New_ID'] + df.columns.tolist()]
>>> df
New_ID ID Fruit
0 880 F1 Apple
1 881 F2 Orange
2 882 F3 Banana
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
Yes. You were missing a '{' under the public class line. And then one at the end of your code to close it.
In swift4,
var Msg_Date_ = "2019-03-30T05:30:00+0000"
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd yyyy h:mm a" //"MMM d, h:mm a" for Sep 12, 2:11 PM
let datee = dateFormatterGet.date(from: Msg_Date_)
Msg_Date_ = dateFormatterPrint.string(from: datee ?? Date())
print(Msg_Date_)
//output :- Mar 30 2019 05:30 PM
If anyone is interested, you can have the the offset information for all the consumer groups with the following command:
kafka-consumer-groups --bootstrap-server localhost:9092 --all-groups --describe
The parameter --all-groups is available from Kafka 2.4.0
BSDs have stat
with different options from the GNU coreutils one, but similar capabilities.
stat -f %z <file name>
This works on macOS (tested on 10.12), FreeBSD, NetBSD and OpenBSD.
declare @d1 datetime, @d2 datetime
select @d1 = '4/19/2017', @d2 = '5/7/2017'
DECLARE @Counter int = datediff(DAY,@d1 ,@d2 )
DECLARE @C int = 0
DECLARE @SUM int = 0
WHILE @Counter > 0
begin
SET @SUM = @SUM + IIF(DATENAME(dw,
DATEADD(day,@c,@d1))IN('Sunday','Monday','Tuesday','Wednesday','Thursday')
,1,0)
SET @Counter = @Counter - 1
set @c = @c +1
end
select @Sum
There's no such thing a the "first n" keys because a dict
doesn't remember which keys were inserted first.
You can get any n key-value pairs though:
n_items = take(n, d.iteritems())
This uses the implementation of take
from the itertools
recipes:
from itertools import islice
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
See it working online: ideone
Update for Python 3.6
n_items = take(n, d.items())
Use this:
$root = 'REST_SERVICE_URL'
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$result = Invoke-RestMethod $root -Credential $credential
As a note ,
for those who need to have null value for things other than "true" or "false" strings , you can use the function below
public Boolean tryParseBoolean(String inputBoolean)
{
if(!inputBoolean.equals("true")&&!inputBoolean.equals("false")) return null;
return Boolean.valueOf(inputBoolean);
}
div {
width:200px;
height:150px;
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
display:box;
box-pack:center;
box-align:center;
}
<div>
<img src="images/logo.png" />
</div>
You can use the jquery-backstretch image which allows for animated slideshows as your background-images!
https://github.com/jquery-backstretch/jquery-backstretch Scroll down to setup and all of the documentation is there.
You can use EXCEPT
in mssql or MINUS
in oracle, they are identical according to :
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
sudo find / -name "pg_config" -print
The answer is /Library/PostgreSQL/9.1/bin/pg_config in my configuration (MAC Maverick)
This is my solution. It works also in Fragment.
webView.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
/usr/local/var/mysql
folderI had MySQL installed with Homebrew, and the only thing that fixed this for me was re-installing MySQL.
On my company laptop, I didn't have permission to uninstall MySQL from my computer via Homebrew:
$ brew uninstall mysql --ignore-dependencies
Uninstalling /usr/local/Cellar/mysql/8.0.12... (255 files, 233.0MB)
Error: Permission denied @ dir_s_rmdir - /usr/local/Cellar/mysql/8.0.12
So instead, I removed and reinstalled MySQL manually:
$ sudo rm -rf /usr/local/Cellar/mysql
$ brew cleanup
$ sudo rm -rf /usr/local/var/mysql
$ brew install mysql
And that worked!
While I agree with the previous answers, it's important to note how to access the code of those external libraries.
For example to access a class in the external library, you will want to use the import keyword followed by the external library's name, continued with dot notation until the desired class is reached.
Look at the image below to see how I import CodeGenerationException class from the quickfixj library.
Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link
This is the issue related to hosts file setup. Add the following line to your hots file In Ububtu: /etc/hosts
127.0.0.1 localhost
In windows: c:\windows\System32\drivers\etc\hosts
127.0.0.1 localhost
Best solution: css + javascript
http://css-tricks.com/select-cuts-off-options-in-ie-fix/
var el;
$("select")
.each(function() {
el = $(this);
el.data("origWidth", el.outerWidth()) // IE 8 can haz padding
})
.mouseenter(function(){
$(this).css("width", "auto");
})
.bind("blur change", function(){
el = $(this);
el.css("width", el.data("origWidth"));
});
Go to database, next to title there are 2 options:
Cloud Firestore, Realtime database
Select Realtime database and go to rules
Change rules to true.
SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);
From the HTTP core module docs:
Example from the documentation:
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
If it's still confusing, here's a longer explanation.
The simplest way to accomplish this is to use two commands.
First, get the local directory into the state that you want. Then,
$ git push origin +HEAD^:someBranch
removes the last commit from someBranch
in the remote only, not local. You can do this a few times in a row, or change +HEAD^
to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use
$ git push origin someBranch
as normal to update the remote.
Return ABDeadlineType
from repository:
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
and then convert to DeadlineType. Manually or use mapstruct.
Or call constructor from @Query
annotation:
public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
@Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
List<DeadlineType> findAllSummarizedBy();
}
Or use @Projection
:
@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {
@Value("#{target.id}")
String getId();
@Value("#{target.code}")
String getText();
}
Update:
Spring can work without @Projection
annotation:
public interface DeadlineType {
String getId();
String getText();
}
You've mixed tabs and spaces. This can lead to some confusing errors.
I'd suggest using only tabs or only spaces for indentation.
Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.
As an aside, your code is more verbose than it needs to be. Instead of this:
if str_p == str_q:
result = True
else:
result = False
return result
Just do this:
return str_p == str_q
You also appear to have a bug on this line:
str_q = p[b+1:]
I'll leave you to figure out what the error is.
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
You can use max_element()
function to find the position of the max element.
int main()
{
int num, arr[10];
int x, y, a, b;
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> arr[i];
}
cout << "Max element Index: " << max_element(arr, arr + num) - arr;
return 0;
}
I have had the same problem and thanks to the posts here I have solved it. I knew that I have around a hundred files and I needed to run it for *.js files only.
find . -type f -name '*.js' -print0 | xargs -0 dos2unix
Thank you all for your help.
App Size for iOS (& tvOS) only
Your app’s total uncompressed size must be less than 4GB. Each Mach-O executable file (for example,
app_name.app/app_name
) must not exceed these limits:
- For apps whose
MinimumOSVersion
is less than 7.0: maximum of 80 MB for the total of all__TEXT
sections in the binary.- For apps whose
MinimumOSVersion
is 7.x through 8.x: maximum of 60 MB per slice for the__TEXT
section of each architecture slice in the binary.- For apps whose
MinimumOSVersion
is 9.0 or greater: maximum of 500 MB for the total of all__TEXT
sections in the binary.However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.
This information can be found at iTunes Connect Developer Guide: Submitting the App to App Review.
(iOS only) App Size
iOS App binary files can be as large as 4 GB, but each executable file (app_name.app/app_name) must not exceed 60 MB. Additionally, the total uncompressed size of the app must be less than 4 billion bytes. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.
This information can be found on page 77 of the iTunes Connect Developer Guide.
(iOS only) App Size
iOS App binary files can be as large as 2 GB, but the executable file (app_name.app/app_name) cannot exceed 60MB. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.
This information can be found on page 58 of the iTunes Connect Developer Guide.
The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 237 of the guide.
The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 208 of the guide.
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 206 of the guide. Thanks to comment from Ozair Kafray.
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 214 of the guide. Thanks to comment from marsbear. In addition, the document has moved here:
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.
The above information is still the same, however, it can be found on page 172 of the guide.
The above information is still the same, however, it can be found on page 180 of the guide. Thanks to comment from Luke for the update.
The above information is still the same, however, it can be found on page 179 of the guide. Thanks to comment from Saxon Druce for the update.
I wouldn't recommend the HAVING
keyword for newbies, it is essentially for legacy purposes.
I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:
I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.
So I've taken a literal interpretation.
The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES
but it could be a VIEW
:
WITH PAYMENT_TALLIES (user_id, zip, tally)
AS
(
SELECT user_id, zip, COUNT(*) AS tally
FROM PAYMENT
GROUP
BY user_id, zip
)
SELECT DISTINCT *
FROM PAYMENT AS P
WHERE EXISTS (
SELECT *
FROM PAYMENT_TALLIES AS PT
WHERE P.user_id = PT.user_id
AND PT.tally > 1
);
Roland's answer is great for this specific problem, but I thought I would share a more generalized approach.
DF <- data.frame(x = letters[1:5], y = 1:5, z = LETTERS[1:5],
stringsAsFactors=FALSE)
str(DF)
# 'data.frame': 5 obs. of 3 variables:
# $ x: chr "a" "b" "c" "d" ...
# $ y: int 1 2 3 4 5
# $ z: chr "A" "B" "C" "D" ...
## The conversion
DF[sapply(DF, is.character)] <- lapply(DF[sapply(DF, is.character)],
as.factor)
str(DF)
# 'data.frame': 5 obs. of 3 variables:
# $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
# $ y: int 1 2 3 4 5
# $ z: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
For the conversion, the left hand side of the assign (DF[sapply(DF, is.character)]
) subsets the columns that are character. In the right hand side, for that subset, you use lapply
to perform whatever conversion you need to do. R is smart enough to replace the original columns with the results.
The handy thing about this is if you wanted to go the other way or do other conversions, it's as simple as changing what you're looking for on the left and specifying what you want to change it to on the right.
If you're using Eclipse PDT, this is done by opening up the PHP explorer view, then clicking the upside-down triangle in the top-right of that window. A context window appears, and the filters option is available there. Clicking the Filters menu option opens a new window, where .* files can be unchecked, thus allowing the editing of .htaccess files.
I searched forever for this, so I'm sorta answering my own question here. I'm sure someone else will have the same problem too, so I hope this helps someone else as well.
It might help who is looking for the same solution.
select * from tablename ORDER BY ABS(column_name)
You can try something like the following:
h1{
margin-bottom:<x>px;
}
div{
margin-bottom:<y>px;
}
div:last-of-type{
margin-bottom:0;
}
or instead of the first h1
rule:
div:first-of-type{
margin-top:<x>px;
}
or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:
div + div{
margin-bottom:<y>px;
}
Respectively, h1 + div
would control the first div after your header, giving you additional styling options.
Well, if Google is cheating on you, you can cheat Google back:
This is the user-agent for pageSpeed:
“Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.8 (KHTML, like Gecko; Google Page Speed Insights) Chrome/19.0.1084.36 Safari/536.8”
You can insert a conditional to avoid serving the analytics script to PageSpeed:
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
// your analytics code here
<?php endif; ?>
Obviously, it won't make any real improvement, but if your only concern is getting a 100/100 score this will do it.
Just a note...
If you add that code to setclasspath.bat or setclasspath.sh, it will actually be used by all of Tomcat's scripts you could run, rather than just Catalina.
The method for setting the variable is as the other's have described.
I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :) Try this:
Use the same connection string in your code too:
Good luck.
keep using the id
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserVerification extends Model
{
protected $table = 'user_verification';
protected $fillable = [
'id',
'email',
'verification_token'
];
//$timestamps = false;
protected $primaryKey = 'verification_token';
}
and get the email :
$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.
There is no such thing as importing in MS SQL. I understand what you mean. It is so simple. Whenever you get/have a something.SQL file, you should just double click and it will directly open in your MS SQL Studio.
Intent promptInstall = new Intent(android.content.Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.parse("http://10.0.2.2:8081/MyAPPStore/apk/Teflouki.apk"), "application/vnd.android.package-archive" );
startActivity(promptInstall);
I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:
((^|, )(part1|part2|part3))+$
Positive matches:
part1
part2, part1
part1, part2, part3
Negative matches:
part1, //with and without trailing spaces.
part3, part2,
otherpart1
Comparing strings in a case insensitive way seems trivial, but it's not. I will be using Python 3, since Python 2 is underdeveloped here.
The first thing to note is that case-removing conversions in Unicode aren't trivial. There is text for which text.lower() != text.upper().lower()
, such as "ß"
:
"ß".lower()
#>>> 'ß'
"ß".upper().lower()
#>>> 'ss'
But let's say you wanted to caselessly compare "BUSSE"
and "Buße"
. Heck, you probably also want to compare "BUSSE"
and "BU?E"
equal - that's the newer capital form. The recommended way is to use casefold
:
str.casefold()
Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. [...]
Do not just use lower
. If casefold
is not available, doing .upper().lower()
helps (but only somewhat).
Then you should consider accents. If your font renderer is good, you probably think "ê" == "e^"
- but it doesn't:
"ê" == "e^"
#>>> False
This is because the accent on the latter is a combining character.
import unicodedata
[unicodedata.name(char) for char in "ê"]
#>>> ['LATIN SMALL LETTER E WITH CIRCUMFLEX']
[unicodedata.name(char) for char in "e^"]
#>>> ['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT']
The simplest way to deal with this is unicodedata.normalize
. You probably want to use NFKD normalization, but feel free to check the documentation. Then one does
unicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "e^")
#>>> True
To finish up, here this is expressed in functions:
import unicodedata
def normalize_caseless(text):
return unicodedata.normalize("NFKD", text.casefold())
def caseless_equal(left, right):
return normalize_caseless(left) == normalize_caseless(right)
The best explanation is here with diagrams:
While a forward proxy proxies on behalf of clients ( or requesting hosts ), a reverse proxy proxies on behalf of servers.
In effect, whereas a forward proxy hides the identities of clients, a reverse proxy hides the identities of servers.
I find this helpful:
function console($data, $priority, $debug)
{
if ($priority <= $debug)
{
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';
echo $output;
}
}
And use it like:
<?php
$debug = 5; // All lower and equal priority logs will be displayed
console('Important', 1 , $debug);
console('Less Important', 2 , $debug);
console('Even Less Important', 5 , $debug);
console('Again Important', 1 , $debug);
?>
Which outputs in console:
Important Less Important Even Less Important Again Important
And you can switch off less important logs by limiting them using the $debug value.
take the underscore out and try again:
console.log(user.id)
Also, the value returned from id is already a string, as you can see here.
I'm using it this way and it works.
Cheers
I think because of the below code you are not getting new credential
string fullName = Request.ServerVariables["LOGON_USER"];
You can try custom login page.
In HTML:
<div ng-repeat="product in products | filter: colorFilter">
In Angular:
$scope.colorFilter = function (item) {
if (item.color === 'red' || item.color === 'blue') {
return item;
}
};
You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.
For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
Other than syntax, a switch can be implemented using a tree which makes it O(log n)
, while a if/else has to be implemented with an O(n)
procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?
Considering that you are using OpenCV, the best way to convert between data types is to use normalize
function.
img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
However, if you don't want to use OpenCV, you can do this in numpy
def convert(img, target_type_min, target_type_max, target_type):
imin = img.min()
imax = img.max()
a = (target_type_max - target_type_min) / (imax - imin)
b = target_type_max - a * imax
new_img = (a * img + b).astype(target_type)
return new_img
And then use it like this
imgu8 = convert(img16u, 0, 255, np.uint8)
This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040
Use DefaultIfEmpty()
instead of FirstOrDefault()
.
In order to use nslookup
, host
or gethostbyname()
then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.
Reference here 2.10.2.1 Troubleshooting Problems Starting the MySQL Server.
1.Find the data directory ,it was configured in my.cnf.
[mysqld]
datadir=/var/lib/mysql
2. Check the err file,it log the error message about why mysql server start failed. the name of err file is related with your hostname.
cd /var/lib/mysql
ll
tail (hostname).err
3.If you find some messages like :
InnoDB: Error: log file ./ib_logfile0 is of different size 0 33554432 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
170513 14:25:22 [ERROR] Plugin 'InnoDB' init function returned error.
170513 14:25:22 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
170513 14:25:22 [ERROR] Unknown/unsupported storage engine: InnoDB
170513 14:25:22 [ERROR] Aborting
then
delete ib_logfile0 and ib_logfile1
, then,
/etc/init.d/mysqld start
There's a lot of comment plugins for vim - a number of which are multi-language - not just python. If you use a plugin manager like Vundle then you can search for them (once you've installed Vundle) using e.g.:
:PluginSearch comment
And you will get a window of results. Alternatively you can just search vim-scripts for comment plugins.
In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
So, you can do this:
var timeoutID = window.setTimeout(function (self) {
console.log(self);
}, 500, this);
This is better in terms of performance than a scope lookup (caching this
into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy
or Function.prototype.bind
).
The code to make it work in IEs from Webreflection:
/*@cc_on
(function (modifierFn) {
// you have to invoke it as `window`'s property so, `window.setTimeout`
window.setTimeout = modifierFn(window.setTimeout);
window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
return function (callback, timeout){
var args = [].slice.call(arguments, 2);
return originalTimerFn(function () {
callback.apply(this, args)
}, timeout);
}
});
@*/
This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.
In this example, clicking on the button changes the background color for a row and then calls repaint.
public class TableTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Color[] rowColors = new Color[] {
randomColor(), randomColor(), randomColor()
};
final JTable table = new JTable(3, 3);
table.setDefaultRenderer(Object.class, new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
JPanel pane = new JPanel();
pane.setBackground(rowColors[row]);
return pane;
}
});
frame.setLayout(new BorderLayout());
JButton btn = new JButton("Change row2's color");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rowColors[1] = randomColor();
table.repaint();
}
});
frame.add(table, BorderLayout.NORTH);
frame.add(btn, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private static Color randomColor() {
Random rnd = new Random();
return new Color(rnd.nextInt(256),
rnd.nextInt(256), rnd.nextInt(256));
}
}
Use stat
like this:
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
Lots of the above helped for me, plus the accepted answer, but since I was on an EC2 instance, I had no idea what my instance name was. Finally, I opened SQLServer Configuration Manager and in the Name column, use whatever is there as your connection server, so in my case, .\EC2SQLEXPRESS and worked great!
There is nothing like kafka --version
at this point. So you should either check the version from your kafka/libs/
folder or you can run
find ./libs/ -name \*kafka_\* | head -1 | grep -o '\kafka[^\n]*'
from your kafka folder (and it will do the same for you). It will return you something like kafka_2.9.2-0.8.1.1.jar.asc
where 0.8.1.1
is your kafka version.
You can use like this for check password contain at-least 1 Uppercase, 1 Lowercase, 1 Numeric and 1 special character :
$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'password' => 'required|confirmed|min:6|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/']);
It seems the answer to your question is no, however one hack you can use is to assign a dummy column to separate each new table. This works especially well if you're looping through a result set for a list of columns in a scripting language such as Python or PHP.
SELECT '' as table1_dummy, table1.*, '' as table2_dummy, table2.*, '' as table3_dummy, table3.* FROM table1
JOIN table2 ON table2.table1id = table1.id
JOIN table3 ON table3.table1id = table1.id
I realize this doesn't answer your question exactly, but if you're a coder this is a great way to separate tables with duplicate column names. Hope this helps somebody.
I needed to find something that would work for multiple popovers and in Bootstrap 3.
Here's what I did:
I had multiple elements I wanted to have a popover work for, so I didn't want to use ids.
The markup could be:
<button class="btn btn-link foo" type="button">Show Popover 1</button>
<button class="btn btn-link foo" type="button">Show Popover 2</button>
<button class="btn btn-link foo" type="button">Show Popover 3</button>
The content for the save and close buttons inside the popover:
var contentHtml = [
'<div>',
'<button class="btn btn-link cancel">Cancel</button>',
'<button class="btn btn-primary save">Save</button>',
'</div>'].join('\n');
and the javascript for all 3 buttons:
This method works when the container is the default not attached to body.
$('.foo').popover({
title: 'Bar',
html: true,
content: contentHtml,
trigger: 'manual'
}).on('shown.bs.popover', function () {
var $popup = $(this);
$(this).next('.popover').find('button.cancel').click(function (e) {
$popup.popover('hide');
});
$(this).next('.popover').find('button.save').click(function (e) {
$popup.popover('hide');
});
});
When the container is attached to 'body'
Then, use the aria-describedby to find the popup and hide it.
$('.foo').popover({
title: 'Bar',
html: true,
content: contentHtml,
container: 'body',
trigger: 'manual'
}).on('shown.bs.popover', function (eventShown) {
var $popup = $('#' + $(eventShown.target).attr('aria-describedby'));
$popup.find('button.cancel').click(function (e) {
$popup.popover('hide');
});
$popup.find('button.save').click(function (e) {
$popup.popover('hide');
});
});
It sounds like what you really want to do is implement an interface.
Your interface will specify the methods that the object can handle and when you pass an object that implements the interface to a method that wants an object that supports the interface, you just type the argument with the name of the interface.
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
The existing answers are all good stuff, but I wanted to share one more little gem that has been valuable in debugging tricky precision issues in a GLSL shader. With very large int numbers represented as a floating point, one needs to take care to use floor(n) and floor(n + 0.5) properly to implement round() to an exact int. It is then possible to render a float value that is an exact int by the following logic to pack the byte components into R, G, and B output values.
// Break components out of 24 bit float with rounded int value
// scaledWOB = (offset >> 8) & 0xFFFF
float scaledWOB = floor(offset / 256.0);
// c2 = (scaledWOB >> 8) & 0xFF
float c2 = floor(scaledWOB / 256.0);
// c0 = offset - (scaledWOB << 8)
float c0 = offset - floor(scaledWOB * 256.0);
// c1 = scaledWOB - (c2 << 8)
float c1 = scaledWOB - floor(c2 * 256.0);
// Normalize to byte range
vec4 pix;
pix.r = c0 / 255.0;
pix.g = c1 / 255.0;
pix.b = c2 / 255.0;
pix.a = 1.0;
gl_FragColor = pix;
Thanks for all the Hints. Using Tomcat8 I also added a filter like @Jasper de Vries wrote. But in the newer Tomcats nowadays there is a filter already implemented that can be used resp just uncommented in the Tomcat web.xml:
<filter>
<filter-name>setCharacterEncodingFilter</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<async-supported>true</async-supported>
</filter>
...
<filter-mapping>
<filter-name>setCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And like all others posted; I added the URIEncoding="UTF-8"
to the Tomcat Connector in Apache. That also helped.
Important to say, that Eclipse (if you use this) has a copy of its web.xml and overwrites the Tomcat-Settings as it was explained here: Broken UTF-8 URI Encoding in JSPs
I would have used stopPropagation
like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
I suggest to use Google Guava Throwables class
propagate(Throwable throwable)
Propagates throwable as-is if it is an instance of RuntimeException or Error, or else as a last resort, wraps it in a RuntimeException and then propagates.**
void bar() {
Stream<A> as = ...
as.forEach(a -> {
try {
a.foo()
} catch(Exception e) {
throw Throwables.propagate(e);
}
});
}
UPDATE:
Now that it is deprecated use:
void bar() {
Stream<A> as = ...
as.forEach(a -> {
try {
a.foo()
} catch(Exception e) {
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
});
}
I was finally able to get this to work for my needs.
The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.
https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.
The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.
Private Sub MySubNamek()
Dim objShell As Object 'Shell
Dim objFolder As Object 'Folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")
If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
For i = 0 To 288
szItem = objFolder.GetDetailsOf(objFolderItem, i)
Debug.Print i & " - " & szItem
Next
Set objFolderItem = Nothing
End If
Set objFolder = Nothing
Set objShell = Nothing
End Sub
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
There is the tabindex property that can be set on component. It specifies in which order the input components should be iterated when selecting one and pressing tab. Values above 0 are reserved for custom navigation, 0 is "in natural order" (so would behave differently if set for the first element), -1 means not keyboard focusable:
<!-- navigate with tab key: -->
<input tabindex="1" type="text"/>
<input tabindex="2" type="text"/>
It can also be set for something else than the text input fields but it is not very obvious what it would do there, if anything at all. Even if the navigation works, maybe better to use "natural order" for anything else than the very obvious user input elements.
No, you do not need JQuery or any scripting at all to support this custom path of navigation. You can implement it on the server side without any JavaScript support. From the other side, the property also works fine in React framework but does not require it.
Specific to only certain builds of Ubuntu. Though it may just tell you 127.0.0.1
:
hostname -i
or
hostname -I
You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.
Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.
"Cannot have multiple items selected in a DropDownList"
This question is very, very, very old, but as a trick in the future, I recommend something like this:
.element{
box-shadow: 0px 0px 10px #232931;
}
.container{
height: 100px;
width: 100px;
overflow: hidden;
}
Basically, you have a box shadow and then wrapping the element in a div with its overflow set to hidden. You'll need to adjust the height, width, and even padding of the div to only show the left box shadow, but it works. See here for an example If you look at the example, you can see how there's no other shadows, but only a black left shadow. Edit: this is a retake of the same screen shot, in case some one thinks that I just cropped out the right. You can find it here
This is an example without the new C++ interface (works for 90, 180 and 270 degrees, using param = 1, 2 and 3). Remember to call cvReleaseImage
on the returned image after using it.
IplImage *rotate_image(IplImage *image, int _90_degrees_steps_anti_clockwise)
{
IplImage *rotated;
if(_90_degrees_steps_anti_clockwise != 2)
rotated = cvCreateImage(cvSize(image->height, image->width), image->depth, image->nChannels);
else
rotated = cvCloneImage(image);
if(_90_degrees_steps_anti_clockwise != 2)
cvTranspose(image, rotated);
if(_90_degrees_steps_anti_clockwise == 3)
cvFlip(rotated, NULL, 1);
else if(_90_degrees_steps_anti_clockwise == 1)
cvFlip(rotated, NULL, 0);
else if(_90_degrees_steps_anti_clockwise == 2)
cvFlip(rotated, NULL, -1);
return rotated;
}
in the end i found a solution First, make sure MySQL server is running. Type the following command at a shell prompt:
/etc/init.d/mysql status
If MySQL is not running, enter:
/etc/init.d/mysql start
If MySQL is not installed, type the following command to install MySQL server:
apt-get install mysql-server
Make sure MySQL module for php5 is installed:
dpkg --list | grep php5-mysql
To install php5-mysql module enter:
apt-get install php5-mysql
Next, restart the Apache2 web server:
/etc/init.d/apache2 restart
If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:
public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T), true);
return atts.Length > 0;
}
which you can use like typeof(Foo).HasAttribute<BarAttribute>();
Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:
ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()
I was searching how to find out prime number and went through above code which are too long. I found out a new easy solution for prime number and add them using filter. Kindly suggest me if there is any mistake in my code as I am a beginner.
function sumPrimes(num) {
let newNum = [];
for(let i = 2; i <= num; i++) {
newNum.push(i)
}
for(let i in newNum) {
newNum = newNum.filter(item => item == newNum[i] || item % newNum[i] !== 0)
}
return newNum.reduce((a,b) => a+b)
}
sumPrimes(10);
Looking at :help tabs it doesn't look like vim wants to work the way you do...
Buffers are shared across tabs, so it doesn't seem possible to lock a given buffer to appear only on a certain tab.
It's a good idea, though.
You could probably get the effect you want by using a terminal that supports tabs, like multi-gnome-terminal, then running vim instances in each terminal tab. Not perfect, though...
This is a simple prove that you cannot destroy an object, you can only destroy a link to it.
$var = (object)['a'=>1];
$var2 = $var;
$var2->a = 2;
unset($var2);
echo $var->a;
returns
2
See it in action here: https://eval.in/1054130
Just to update this question for mod_security 2.7.0+ - they turned off the ability to mitigate modsec via htaccess unless you compile it with the --enable-htaccess-config
flag. Most hosts do not use this compiler option since it allows too lax security. Instead, vhosts in httpd.conf are your go-to option for controlling modsec.
Even if you do compile modsec with htaccess mitigation, there are less directives available. SecRuleEngine
can no longer be used there for example. Here is a list that is available to use by default in htaccess if allowed (keep in mind a host may further limit this list with AllowOverride
):
- SecAction
- SecRule
- SecRuleRemoveByMsg
- SecRuleRemoveByTag
- SecRuleRemoveById
- SecRuleUpdateActionById
- SecRuleUpdateTargetById
- SecRuleUpdateTargetByTag
- SecRuleUpdateTargetByMsg
More info on the official modsec wiki
As an additional note for 2.x users: the IfModule
should now look for mod_security2.c
instead of the older mod_security.c
One more implementation (in Java). May not be most efficient solution but # of iterations is same as that of Exponential solution.
public static long pow(long base, long exp){
if(exp ==0){
return 1;
}
if(exp ==1){
return base;
}
if(exp % 2 == 0){
long half = pow(base, exp/2);
return half * half;
}else{
long half = pow(base, (exp -1)/2);
return base * half * half;
}
}
If you want to use this in VBA:
For i = 1 To X
UserForm1.Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like
public class Test
{
public final int a = 3;
or as a local variable, like
public static void main(String[] args)
{
final int a = 3;
If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.
public class Test
{
public int a;
public void doSomething()
{
Runnable runnable =
new Runnable()
{
public void run()
{
System.out.println(a);
a = a+1;
}
};
}
}
You can't have a variable as final and give it a new value. final
means just that: the value is unchangeable and final.
And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).
It just copies over the value of a into an implicit int called a in your anonymous class.
The differences are
String class is overriding toString(), equals(), hashCode() of Object class, but StringBuffer only overrides toString().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // output true
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); // output false
String class is both Serializable as well as Comparable, but StringBuffer is only Serializable.
Set<StringBuffer> set = new TreeSet<StringBuffer>();
set.add(sb1);
set.add(sb2);
System.out.println(set); // gives ClassCastException because there is no Comparison mechanism
We can create a String object with and without new operator, but StringBuffer object can only be created using new operator.