I got it to work, but the solution is a bit complex, so bear with me.
As it is, Internet Explorer gives lower level of trust to IFRAME pages (IE calls this "third-party" content). If the page inside the IFRAME doesn't have a Privacy Policy, its cookies are blocked (which is indicated by the eye icon in status bar, when you click on it, it shows you a list of blocked URLs).
(source: piskvor.org)
In this case, when cookies are blocked, session identifier is not sent, and the target script throws a 'session not found' error.
(I've tried setting the session identifier into the form and loading it from POST variables. This would have worked, but for political reasons I couldn't do that.)
It is possible to make the page inside the IFRAME more trusted: if the inner page sends a P3P header with a privacy policy that is acceptable to IE, the cookies will be accepted.
A good starting point is the W3C tutorial. I've gone through it, downloaded the IBM Privacy Policy Editor and there I created a representation of the privacy policy and gave it a name to reference it by (here it was policy1
).
NOTE: at this point, you actually need to find out if your site has a privacy policy, and if not, create it - whether it collects user data, what kind of data, what it does with it, who has access to it, etc. You need to find this information and think about it. Just slapping together a few tags will not cut it. This step cannot be done purely in software, and may be highly political (e.g. "should we sell our click statistics?").
(e.g. "the site is operated by ACME Ltd., it uses anonymous per-session identifiers for its operation, collects user data only if explicitly permitted and only for the following purposes, the data is stored only as long as necessary, only our company has access to it, etc. etc.").
(When editing with this tool, it's possible to view errors/omissions in the policy. Also very useful is the tab "HTML Policy": at the bottom, it has a "Policy Evaluation" - a quick check if the policy will be blocked by IE's default settings)
The Editor exports to a .p3p file, which is an XML representation of the above policy. Also, it can export a "compact version" of this policy.
Then a Policy Reference file (http://example.com/w3c/p3p.xml
) was needed (an index of privacy policies the site uses):
<META>
<POLICY-REFERENCES>
<POLICY-REF about="/w3c/example-com.p3p#policy1">
<INCLUDE>/</INCLUDE>
<COOKIE-INCLUDE/>
</POLICY-REF>
</POLICY-REFERENCES>
</META>
The <INCLUDE>
shows all URIs that will use this policy (in my case, the whole site). The policy file I've exported from the Editor was uploaded to http://example.com/w3c/example-com.p3p
I've set the webserver at example.com to send the compact header with responses, like this:
HTTP/1.1 200 OK
P3P: policyref="/w3c/p3p.xml", CP="IDC DSP COR IVAi IVDi OUR TST"
// ... other headers and content
policyref
is a relative URI to the Policy Reference file (which in turn references the privacy policies), CP
is the compact policy representation. Note that the combination of P3P headers in the example may not be applicable on your specific website; your P3P headers MUST truthfully represent your own privacy policy!
In this configuration, the Evil Eye does not appear, the cookies are saved even in the IFRAME, and the application works.
Several people have suggested "just slap some tags into your P3P header, until the Evil Eye gives up".
The tags are not only a bunch of bits, they have real world meanings, and their use gives you real world responsibilities!
For example, pretending that you never collect user data might make the browser happy, but if you actually collect user data, the P3P is conflicting with reality. Plain and simple, you are purposefully lying to your users, and that might be criminal behavior in some countries. As in, "go to jail, do not collect $200".
A few examples (see p3pwriter for the full set of tags):
STP
but don't have a retention policy, you may be committing fraud. How cool is that? Not at all.)I'm not a lawyer, but I'm not willing to go to court to see if the P3P header is really legally binding or if you can promise your users anything without actually willing to honor your promises.
You can run npx webpack
. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package.
Source of info: https://webpack.js.org/guides/getting-started/
Instead of using a dot, like: 1.2, try to input like this: 1,2.
Just my two cents.
To overcome the requirement of CountDownLatch
to know the number of tasks beforehand, you could do it the old fashion way by using a simple Semaphore
.
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
int numberOfTasks=0;
Semaphore s=new Semaphore(0);
while(...) {
taskExecutor.execute(new MyTask());
numberOfTasks++;
}
try {
s.aquire(numberOfTasks);
...
In your task just call s.release()
as you would latch.countDown();
If each side of the rectangle is a line segment, and the user drawn portion is a line segment, then you need to just check the user drawn segment for intersection with the four side line segments. This should be a fairly simple exercise given the start and end points of each segment.
All you have to do is : Go to Data tab Chose advanced in Sort & Filter In actions select : copy to another location if want a new list - Copy to any location In list range chose the list you want to get the records off . And the most important thing is to check : Unique records only .
inside class,
final usernameController = TextEditingController(text: 'bhanuka');
TextField,
child: new TextField(
controller: usernameController,
...
)
Do this with a file stream. When a std::ofstream
is closed, the file is created. I personally like the following code, because the OP only asks to create a file, not to write in it:
#include <fstream>
int main()
{
std::ofstream file { "Hello.txt" };
// Hello.txt has been created here
}
The temporary variable file
is destroyed right after its creation, so the stream is closed and thus the file is created.
If you are like me whose Java Control Panel does not show Security slider under Security Tab to change security level from High to Medium then follow these instructions: Java known bug: security slider not visible.
After installation, the checkbox to enable/disable Java and the security level slider do not appear in the Java Control Panel Security tab. This can occur with 7u10 and above.
This is due to a conflict that Java 7u10 and above have with standalone installations of JavaFX. Example: If Java 7u5 and JavaFX 2.1.1 are installed and if Java is updated to 7u11, the Java Control Panel does not show the checkbox or security slider.
It is recommended to uninstall all versions of Java and JavaFX before installing Java 7u10 and above.
Please follow the steps below for resolving this issue.
1. Remove all versions of Java and JavaFX through the Windows Uninstall Control Panel. Instructions on uninstalling Java.
2. Run the Microsoft uninstall utility to repair corrupted registry keys that prevents programs from being completely uninstalled or blocking new installations and updates.
3. Download and install the Windows offline installer package.
Login into the database. then run the below query
select * from dba_role_privs where grantee = 'SCHEMA_NAME';
All the role granted to the schema will be listed.
Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.
I had a similar issue, because of my replication binary logs.
If this is the case, just create a cronjob to run this query every day:
PURGE BINARY LOGS BEFORE DATE_SUB( NOW(), INTERVAL 2 DAY );
This will remove all binary logs older than 2 days.
I found this solution here.
Had the same problem on my Win10 PC with different packages and tried everything mentioned so far.
Finally solved it by disabling Comodo Auto-Containment.
Since nobody has mentioned it yet, I hope it helps someone.
Run this first
df.createOrReplaceTempView('df')
Then run
spark.sql("""
SELECT distinct
column name
FROM
df
""").show()
You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:
var lr = new LocalReport
{
ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
EnableExternalImages = true
};
lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
string mimeType, encoding, extension;
Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
(
"PDF",
@"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
out mimeType,
out encoding,
out extension,
out streams,
out warnings
);
var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
var idx = 0;
while (File.Exists(saveAs))
{
idx++;
saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}
using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
stream.Write(renderedBytes, 0, renderedBytes.Length);
stream.Close();
}
lr.Dispose();
You can also add parameters: (lr.SetParameter())
, handle subreports: (lr.SubreportProcessing+=YourHandler)
, or pretty much anything you can think of.
Place the body of your loop after the while
and before the test. The actual body of the while
loop should be a no-op.
while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
:
done
Instead of the colon, you can use continue
if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5
. Or print delimiters between values:
i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'
I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <=
are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.
The answer posted by @schellack is perfect for most scenarios, but I wanted Beyond Compare to simulate the '2 Way merge with a result panel' view that Visual Studio uses in its own merge window.
This config hides the middle panel (which is unused in most cases AFAIK).
%1 %2 "" %4 /title1=%6 /title2=%7 /title3="" /title4=%9
With thanks to Morgen
I create this program:
import pygame, sys, time, random, easygui
skier_images = ["skier_down.png", "skier_right1.png",
"skier_right2.png", "skier_left2.png",
"skier_left1.png"]
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0
def turn(self, direction):
self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed
def move(self,speed):
self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self,image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False
def scroll(self, t_ptr):
self.rect.centery = self.location[1] - t_ptr
def create_map(start, end):
obstacles = pygame.sprite.Group()
gates = pygame.sprite.Group()
locations = []
for i in range(10):
row = random.randint(start, end)
col = random.randint(0, 9)
location = [col * 64 + 20, row * 64 + 20]
if not (location in locations) :
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)
return obstacles
def animate():
screen.fill([255,255,255])
pygame.display.update(obstacles.draw(screen))
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10,10])
pygame.display.flip()
def updateObstacleGroup(map0, map1):
obstacles = pygame.sprite.Group()
for ob in map0: obstacles.add(ob)
for ob in map1: obstacles.add(ob)
return obstacles
pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None, 50)
a = True
while a:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT:
speed = skier.turn(1)
skier.move(speed)
map_position += speed[1]
if map_position >= 640 and activeMap == 0:
activeMap = 1
map0 = create_map(20, 29)
obstacles = updateObstacleGroup(map0, map1)
if map_position >=1280 and activeMap == 1:
activeMap = 0
for ob in map0:
ob.location[1] = ob.location[1] - 1280
map_position = map_position - 1280
map1 = create_map(10, 19)
obstacles = updateObstacleGroup(map0, map1)
for obstacle in obstacles:
obstacle.scroll(map_position)
hit = pygame.sprite.spritecollide(skier, obstacles, False)
if hit:
if hit[0].type == "tree" and not hit[0].passed:
skier.image = pygame.image.load("skier_crash.png")
easygui.msgbox(msg="OOPS!!!")
choice = easygui.buttonbox("Do you want to play again?", "Play", ("Yes", "No"))
if choice == "Yes":
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
elif choice == "No":
a = False
quit()
elif hit[0].type == "flag" and not hit[0].passed:
points += 10
obstacles.remove(hit[0])
score_text = font.render("Score: " + str(points), 1, (0, 0, 0))
animate()
Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit
\begin{figure}[H]
\centering
{\includegraphics[width=1.0\textwidth]{image}}
\caption{captiontext\protect\footnotemark}
\label{fig:}
\end{figure}
\footnotetext{Footnotetext}
Yes, you can use any of these popular tools:
This is pure set theory which you can achieve with the minus
operation.
select id, name from table1
minus
select id, name from table2
This will work from JS without coupling to HTML:
document.getElementById("click-button").onclick = onClickFunction;
function onClickFunction()
{
return functionWithArguments('You clicked the button!');
}
function functionWithArguments(text) {
document.getElementById("some-div").innerText = text;
}
Please try this, if you want to fetch first/last.
{{#each list}}
{{#if @first}}
<div class="active">
{{else}}
<div>
{{/if}}
{{/each}}
{{#each list}}
{{#if @last}}
<div class="last-element">
{{else}}
<div>
{{/if}}
{{/each}}
The biggest remaining reason is specialization.
Redis can do a lot of different things and one side effect of that is developers may start using a lot of those different feature sets on the same instance. If you're using the LRU feature of Redis for a cache along side hard data storage that is NOT LRU it's entirely possible to run out of memory.
If you're going to setup a dedicated Redis instance to be used ONLY as an LRU instance to avoid that particular scenario then there's not really any compelling reason to use Redis over Memcached.
If you need a reliable "never goes down" LRU cache...Memcached will fit the bill since it's impossible for it to run out of memory by design and the specialize functionality prevents developers from trying to make it so something that could endanger that. Simple separation of concerns.
The advantages are that you can use functions like LEN
and LEFT
on nvarchar(max)
and you cannot do that against ntext
and text
. It is also easier to work with nvarchar(max)
than text
where you had to use WRITETEXT
and UPDATETEXT
.
Also, text
, ntext
, etc., are being deprecated (http://msdn.microsoft.com/en-us/library/ms187993.aspx)
You're mixing the parts together instead of separating them cleanly.
printf '\e[1;34m%-6s\e[m' "This is text"
Basically, put the fixed stuff in the format and the variable stuff in the parameters.
Same with something more complex...getting the ec2 instance region from within the instance.
INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")
echo $INSTANCE_REGION
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
Here is a Javascript version that returns a function that does the rescaling for predetermined source and destination ranges, minimizing the amount of computation that has to be done each time.
// This function returns a function bound to the
// min/max source & target ranges given.
// oMin, oMax = source
// nMin, nMax = dest.
function makeRangeMapper(oMin, oMax, nMin, nMax ){
//range check
if (oMin == oMax){
console.log("Warning: Zero input range");
return undefined;
};
if (nMin == nMax){
console.log("Warning: Zero output range");
return undefined
}
//check reversed input range
var reverseInput = false;
let oldMin = Math.min( oMin, oMax );
let oldMax = Math.max( oMin, oMax );
if (oldMin != oMin){
reverseInput = true;
}
//check reversed output range
var reverseOutput = false;
let newMin = Math.min( nMin, nMax )
let newMax = Math.max( nMin, nMax )
if (newMin != nMin){
reverseOutput = true;
}
// Hot-rod the most common case.
if (!reverseInput && !reverseOutput) {
let dNew = newMax-newMin;
let dOld = oldMax-oldMin;
return (x)=>{
return ((x-oldMin)* dNew / dOld) + newMin;
}
}
return (x)=>{
let portion;
if (reverseInput){
portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);
} else {
portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
}
let result;
if (reverseOutput){
result = newMax - portion;
} else {
result = portion + newMin;
}
return result;
}
}
Here is an example of using this function to scale 0-1 into -0x80000000, 0x7FFFFFFF
let normTo32Fn = makeRangeMapper(0, 1, -0x80000000, 0x7FFFFFFF);
let fs = normTo32Fn(0.5);
let fs2 = normTo32Fn(0);
The ListView control uses the Items collection to add items to listview in the control and is able to customize items.
You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):
C:\>tnsping dev
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)
C:\>
Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.
In my case, six was installed for python 2.7 and for 3.7 too, and both pip install six
and pip3 install six
reported it as already installed, while I still had apps (particularly, the apt program itself) complaining about missing six.
The solution was to install it for python3.6 specifically:
/usr/bin/python3.6 -m pip install six
Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.
There is this possibility like Aman Virk mentioned:
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
But keep in mind that the padding and margin aren't there to bother you. If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.
If you take away that margin then you will end up showing only a part of the labels or no labels at all.
So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.
Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:
<root>
<level value="ALL" />
<appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
<level value="ALL" />
<appender-ref ref="File1Appender2" />
</logger>
This is how I have done it in the past. Then something like this for the other log:
private static readonly ILog otherLog = LogManager.GetLogger("SomeName");
And you can get your normal logger as follows:
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Read the loggers and appenders section of the documentation to understand how this works.
I went with "manually" using the same breakpoints in Bootstrap 4 as media queries...
/* Equal-height card images, cf. https://stackoverflow.com/a/47698201/1375163*/
.card-img-top {
/*height: 11vw;*/
object-fit: cover;
}
/* Small devices (landscape phones, 576px and up) */
@media (min-width: 576px) {
.card-img-top {
height: 19vw;
}
}
/* Medium devices (tablets, 768px and up) */
@media (min-width: 768px) {
.card-img-top {
height: 16vw;
}
}
/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
.card-img-top {
height: 11vw;
}
}
/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 992px) {
.card-img-top {
height: 11vw;
}
}
It works, though I wish there were more native responsiveness of this sort.
Partial suggestion from @sepuckett86 and I.
For French Locale (France) ONLY, be careful because /
appears in the date :
echo %DATE%
08/09/2013
For our problem of log file, here is my proposal for French Locale ONLY:
SETLOCAL
set LOGFILE_DATE=%DATE:~6,4%.%DATE:~3,2%.%DATE:~0,2%
set LOGFILE_TIME=%TIME:~0,2%.%TIME:~3,2%
set LOGFILE=log-%LOGFILE_DATE%-%LOGFILE_TIME%.txt
rem log-2014.05.19-22.18.txt
command > %LOGFILE%
I found the best way to solving this problem was a combination of trial and error and reading what was written before me:
As you can see I have some pretty tricky stuff going on... but the main kicker of getting this to looking good are:
PARENT ELEMENT (UL): border-collapse: separate; border-spacing: .25em; margin-left: -.25em;
CHILD ELEMENTS (LI): display: table-cell; vertical-align: middle;
HTML
<ul>
<li><span class="large">3</span>yr</li>
<li>in<br>stall</li>
<li><span class="large">9</span>x<span class="large">5</span></li>
<li>on<br>site</li>
<li>globe</li>
<li>back<br>to hp</li>
</ul>
CSS
ul { border: none !important; border-collapse: separate; border-spacing: .25em; margin: 0 0 0 -.25em; }
li { background: #767676 !important; display: table-cell; vertical-align: middle; position: relative; border-radius: 5px 0; text-align: center; color: white; padding: 0 !important; font-size: .65em; width: 4em; height: 3em; padding: .25em !important; line-height: .9; text-transform: uppercase; }
I'd move to lists and solve it this way:
The code would be more or less like this:
/* Main method */
private void execute(Collection<Foo> oldSet, Collection<Foo> newSet) {
List<Foo> oldList = asSortedList(oldSet);
List<Foo> newList = asSortedList(newSet);
int oldIndex = 0;
int newIndex = 0;
// Iterate over both collections but not always in the same pace
while( oldIndex < oldList.size()
&& newIndex < newIndex.size()) {
Foo oldObject = oldList.get(oldIndex);
Foo newObject = newList.get(newIndex);
// Your logic here
if(oldObject.getId() < newObject.getId()) {
doRemove(oldObject);
oldIndex++;
} else if( oldObject.getId() > newObject.getId() ) {
doAdd(newObject);
newIndex++;
} else if( oldObject.getId() == newObject.getId()
&& isModified(oldObject, newObject) ) {
doUpdate(oldObject, newObject);
oldIndex++;
newIndex++;
} else {
...
}
}// while
// Check if there are any objects left in *oldList* or *newList*
for(; oldIndex < oldList.size(); oldIndex++ ) {
doRemove( oldList.get(oldIndex) );
}// for( oldIndex )
for(; newIndex < newList.size(); newIndex++ ) {
doAdd( newList.get(newIndex) );
}// for( newIndex )
}// execute( oldSet, newSet )
/** Create sorted list from collection
If you actually perform any actions on input collections than you should
always return new instance of list to keep algorithm simple.
*/
private List<Foo> asSortedList(Collection<Foo> data) {
List<Foo> resultList;
if(data instanceof List) {
resultList = (List<Foo>)data;
} else {
resultList = new ArrayList<Foo>(data);
}
Collections.sort(resultList)
return resultList;
}
Update: Apparently possible by passing a flag to mysql_connect()
. See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_
-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
This can be done by using SUMPRODUCT
as well. Update the ranges as you see fit
=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)
A2:A7 = First name range
B2:B7 = Last Name Range
C2:C7 = Numbers Range
This will find all the names with the same first and last name and sum the numbers in your numbers column
A simple question should be followed by a short, simple and clear answer.
When we are getting a value of the property it fires its get{}
part.
When we are setting a value to the property it fires its set{}
part.
PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{}
part.
Example:
var A:Int = 0
var B:Int = 0
var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
B = newValue
}
}
//When we are getting a value of C it fires get{} part of C property
A = C
A //Now A = 1
//When we are setting a value to C it fires set{} part of C property
C = 2
B //Now B = 2
Try:
if (record.has("problemkey") && !record.isNull("problemkey")) {
// Do something with object.
}
var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";
if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.
df[["product_id","customer_id","store_id"]]
You need to set map null to that marker.
var markersList = [];
function removeMarkers(markersList) {
for(var i = 0; i < markersList.length; i++) {
markersList[i].setMap(null);
}
}
function addMarkers() {
var marker = new google.maps.Marker({
position : {
lat : 12.374,
lng : -11.55
},
map : map
});
markersList.push(marker);
}
Check the local.properties file in your Studio Project. Chances are that the property sdk.dir points to the wrong folder if you had set/configured a previous android sdk from pre-studio era. This was the solution in my case.
Get the full Android-SDK plus the dependencies at http://developer.android.com/sdk/index.html.
Do have Java installed :)
To disable a submit button, you just need to add a disabled attribute to the submit button.
$("#btnSubmit").attr("disabled", true);
To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.
$('#btnSubmit').attr("disabled", false);
or
$('#btnSubmit').removeAttr("disabled");
This may be achieved by using AppCompatCheckBox
. You can use app:buttonCompat="@drawable/selector_drawable"
to change the selector.
It's working with PNGs, but I didn't find a way for it to work with Vector Drawables.
Enter this in the custom number format field:
[>=1000]#,##0,"K€";0"€"
What that means is that if the number is greater than 1,000, display at least one digit (indicated by the zero), but no digits after the thousands place, indicated by nothing coming after the comma. Then you follow the whole thing with the string "K".
Edited to add comma and euro.
Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.
I tried
kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')
and it works for me.
You can use string utf8_encode( string $data )
function to accomplish what you want. It is for a single string. You can write your own function using which you can convert an array with the help of utf8_encode function.
Your project is missing the support library from the SDK.
If you have no installed them, just right click on the project > Android Tools > Install support library
.
Then, just import into workspace, as an Android project, android-support-v7-appcompat
, located into ${android-sdk-path}/extras/android/support/v7
And finally, right click in the Android project > Properties > Android Tab
. Push the Add
button and add the support project "android-support-v7-appcompat"
as dependency.
Clean your project and the must compile and work properly.
"start" is a name of a script, in npm you run scripts like this npm run scriptName
, npm start
is also a short for npm run start
As for "react-scripts" this is a script related specifically to create-react-app
By definition, the put
command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).
The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null
if none present), so you can determine what was there and maintain a reference if necessary.
More information here: HashMap Doc
And I like this way:
$cars = array
(
array("Volvo",22),
array("BMW",15),
array("Saab",5),
array("Land Rover",17)
);
One solution would be to use the plt.legend
function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc
keyterm. More information can be found at this website but I've also included an example showing how to place a legend:
ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2)
Note that because loc=2
, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize
, which will then make the legend smaller.
Is there a way to handle form post data in a Web Api controller?
The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:
public void Post(NameValueCollection formData)
{
var value = formData["key"];
}
This will match a single non-ASCII character:
[^\x00-\x7F]
This is a valid PCRE (Perl-Compatible Regular Expression).
You can also use the POSIX shorthands:
[[:ascii:]]
- matches a single ASCII char[^[:ascii:]]
- matches a single non-ASCII char[^[:print:]]
will probably suffice for you.**
Just sharing another approach:
First set the list view's android:animateLayoutChanges to true:
<ListView
android:id="@+id/items_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"/>
Then I use a handler to add items and update the listview with delay:
Handler mHandler = new Handler();
//delay in milliseconds
private int mInitialDelay = 1000;
private final int DELAY_OFFSET = 1000;
public void addItem(final Integer item) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
mDataSet.add(item);
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
}).start();
}
}, mInitialDelay);
mInitialDelay += DELAY_OFFSET;
}
select *
into new_table
from table_A
UNION
Select *
From table_B
This only works if Table_A and Table_B have the same schemas
Essentially you need to do an argsort
, what implementation you need depends if you want to use external libraries (e.g. NumPy) or if you want to stay pure-Python without dependencies.
The question you need to ask yourself is: Do you want the
Unfortunately the example in the question doesn't make it clear what is desired because both will give the same result:
>>> arr = np.array([1, 2, 3, 100, 5])
>>> np.argsort(np.argsort(arr))
array([0, 1, 2, 4, 3], dtype=int64)
>>> np.argsort(arr)
array([0, 1, 2, 4, 3], dtype=int64)
argsort
implementationIf you have NumPy at your disposal you can simply use the function numpy.argsort
or method numpy.ndarray.argsort
.
An implementation without NumPy was mentioned in some other answers already, so I'll just recap the fastest solution according to the benchmark answer here
def argsort(l):
return sorted(range(len(l)), key=l.__getitem__)
To get the indices that would sort the array/list you can simply call argsort
on the array or list. I'm using the NumPy versions here but the Python implementation should give the same results
>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(arr)
array([1, 2, 0, 3], dtype=int64)
The result contains the indices that are needed to get the sorted array.
Since the sorted array would be [1, 2, 3, 4]
the argsorted array contains the indices of these elements in the original.
1
and it is at index 1
in the original so the first element of the result is 1
. 2
is at index 2
in the original so the second element of the result is 2
. 3
is at index 0
in the original so the third element of the result is 0
. 4
and it is at index 3
in the original so the last element of the result is 3
.In this case you would need to apply argsort
twice:
>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(np.argsort(arr))
array([2, 0, 1, 3], dtype=int64)
In this case :
3
, which is the third largest value so it would have index 2
in the sorted array/list so the first element is 2
.1
, which is the smallest value so it would have index 0
in the sorted array/list so the second element is 0
.2
, which is the second-smallest value so it would have index 1
in the sorted array/list so the third element is 1
.4
which is the largest value so it would have index 3
in the sorted array/list so the last element is 3
.You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
There are two ways to go about this:
I recommend the first option initially, due to its ease of implementation. Once you mature in your build processes, switch over to the second.
Poll the repository to see if changes occurred. This might "skip" a commit if two commits come in within the same polling interval. Description of how to do so here, note the fourth screenshot where you configure on the job a "build trigger" based on polling the repository (with a crontab-like configuration).
Configure your repository to have a post-commit hook which notifies Jenkins that a build needs to start. Description of how to do so here, in the section "post-commit hooks"
The SVN Tag feature is not part of the polling, it is part of promoting the current "head" of the source code to a tag, to snapshot a build. This allows you to refer to Jenkins buid #32 as SVN tag /tags/build-32 (or something similar).
Try out this one: "Pao" at http://pao-ide.info . It's still in development and not up to production use but it's quite unique in features. Basically, all the language constructs, such as assemblies, types, members, statements, expressions are treated as objects and are associated with rich operation options. You can enjoy features usually seen in graphical editors, such as multiple selection, multiple copy-paste, tagging, batch operation and very powerful search capability. It takes some getting used to but eventually might increase productivity. Right now, it only supports form applications though.
<style>
.nowrap {
white-space: nowrap;
}
</style>
...
<label for="id1" class="nowrap">label1:
<input type="text" id="id1"/>
</label>
Wrap your inputs within the label tag
For ExcelDataReader v3.6.0 and above. I struggled a bit to iterate over the Rows. So here's a little more to the above code. Hope it helps for few atleast.
using (var stream = System.IO.File.Open(copyPath, FileMode.Open, FileAccess.Read))
{
IExcelDataReader excelDataReader = ExcelDataReader.ExcelReaderFactory.CreateReader(stream);
var conf = new ExcelDataSetConfiguration()
{
ConfigureDataTable = a => new ExcelDataTableConfiguration
{
UseHeaderRow = true
}
};
DataSet dataSet = excelDataReader.AsDataSet(conf);
//DataTable dataTable = dataSet.Tables["Sheet1"];
DataRowCollection row = dataSet.Tables["Sheet1"].Rows;
//DataColumnCollection col = dataSet.Tables["Sheet1"].Columns;
List<object> rowDataList = null;
List<object> allRowsList = new List<object>();
foreach (DataRow item in row)
{
rowDataList = item.ItemArray.ToList(); //list of each rows
allRowsList.Add(rowDataList); //adding the above list of each row to another list
}
}
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
For my purposes I wanted all English ASCII chars, so this worked.
html = Regex.Replace(html, "[^\x00-\x80]+", "")
Jest's setupFiles
is the proper way to handle this, and you need not install dotenv
, nor use an .env
file at all, to make it work.
jest.config.js
:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
.jest/setEnvVars.js
:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
That's it.
For PDO You may do this
$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')";
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";
$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);
BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;
Why use normal jquery ajax feature. Why not use jquery ajax form plugin, which post the form data by ajax to the form action link.
Check it here:
http://malsup.com/jquery/form/#getting-started
It is very easy to use and support several data formats including json, html xml etc. Checkout the example and you will find it very easy to use.
Thank you
This worked for me :
npm install -g local-cors-proxy
API endpoint that we want to request that has CORS issues:
https://www.yourdomain.com/test/list
Start Proxy:
lcp --proxyUrl https://www.yourdomain.com
Proxy Active
Proxy Url: http://www.yourdomain.com:28080
Proxy Partial: proxy
PORT: 8010
Then in your client code, new API endpoint:
http://localhost:8010/proxy/test/list
End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!
Sometimes you need to apply a function to the members of a list in place. The following code worked for me:
>>> def func(a, i):
... a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']
Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place
Just a minor addition: The speed difference between memcpy()
and std::copy()
can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy()
clearly wins:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 17 ns 17 ns 40867738
bm_stdcopy 62 ns 62 ns 11176219
bm_stdcopy_n 72 ns 72 ns 9481749
When optimizations are enabled (-O3
), everything looks pretty much the same again:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 3 ns 3 ns 274527617
bm_stdcopy 3 ns 3 ns 272663990
bm_stdcopy_n 3 ns 3 ns 274732792
The bigger the array the less noticeable the effect gets, but even at N=1000
memcpy()
is about twice as fast when optimizations aren't enabled.
Source code (requires Google Benchmark):
#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>
constexpr int N = 10;
void bm_memcpy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
memcpy(r.data(), a.data(), N * sizeof(int));
}
}
void bm_stdcopy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy(a.begin(), a.end(), r.begin());
}
}
void bm_stdcopy_n(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy_n(a.begin(), N, r.begin());
}
}
BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);
BENCHMARK_MAIN()
/* EOF */
You can revert individual commits with:
git revert <commit_hash>
This will create a new commit which reverts the changes of the commit you specified. Note that it only reverts that specific commit and not commits after that. If you want to revert a range of commits, you can do it like this:
git revert <oldest_commit_hash>..<latest_commit_hash>
It reverts the commits between and including the specified commits.
To know the hash of the commit(s) you can use git log
Look at the git-revert man page for more information about the git revert
command. Also, look at this answer for more information about reverting commits.
You can activate JVM's debugging capability when starting up the java
command with a special option:
java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar
Starting up jar.jar
like that on the command line will:
server=y
) listening on port 8000 (address=8000
)Listening for transport dt_socket at address: 8000
to stdout
andsuspend=y
) until some debugger connects. The debugger acts as the client in this scenario.Common options for selecting a debugger are:
jar.jar
should begin executing.jdb -connect com.sun.jdi.SocketAttach:port=8000
jQuery has very helpful function called serialize.
Demo: http://jsfiddle.net/55xnJ/2/
//Just type:
$("#preview_form").serialize();
//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
MySQL doesn't reduce the size of ibdata1. Ever. Even if you use optimize table
to free the space used from deleted records, it will reuse it later.
An alternative is to configure the server to use innodb_file_per_table
, but this will require a backup, drop database and restore. The positive side is that the .ibd file for the table is reduced after an optimize table
.
It is because you set the width:100%
which by definition only spans the width of the screen. You want to set the min-width:100%
which sets it to the width of the screen... with the ability to grow beyond that.
Also make sure you set min-width:100%
for body
and html
.
variable=10
f=open("fileName.txt","w+") # file name and mode
for x in range(0,10):
f.writelines('your text')
f.writelines('if you want to add variable data'+str(variable))
# to add data you only add String data so you want to type cast variable
f.writelines("\n")
You should pass @item.email
in quotes then it will be treated as string argument
<td><a href ="#" onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a> </td>
Otherwise, it is treated as variable thus error is generated.
This worked for me:
app.use(function(req,res,next) {
if(req.headers["x-forwarded-proto"] == "http") {
res.redirect("https://[your url goes here]" + req.url, next);
} else {
return next();
}
});
You can go to jwt.io
, paste your token and read the contents. This is jarring for a lot of people initially.
The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.
The logical question is what is the motivation for not concerning itself with encrypted contents?
The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure
(is not transmitted via HTTP, only via HTTPS) and httpOnly
(can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.
This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).
JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.
It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
Unfortunately the only way I could resolve my problem is to root the device.
Here is a good tutorial for Nexus S:
http://nexusshacks.com/nexus-s-root/how-to-root-nexus-s-or-nexus-s-4g-on-ics-or-gingerbread/
This will work!
$(document).ready(function ()
{
$.ajax(
{
type: 'POST',
url: "/Home/MethodName",
success: function (data) {
//data is the string that the method returns in a json format, but in string
var jsonData = JSON.parse(data); //This converts the string to json
for (var i = 0; i < jsonData.length; i++) //The json object has lenght
{
var object = jsonData[i]; //You are in the current object
$('#olListId').append('<li class="someclass>' + object.Atributte + '</li>'); //now you access the property.
}
/* JSON EXAMPLE
[{ "Atributte": "value" },
{ "Atributte": "value" },
{ "Atributte": "value" }]
*/
}
});
});
The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.
Quick example:
On Ubuntu, if you are interested, for instance, in Gmail then open the Terminal and type:
nslookup -q=mx gmail.com
This worked for me:
.container {_x000D_
display: inline-flex;_x000D_
}_x000D_
_x000D_
.slide {_x000D_
float: left;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="slide">something1</div>_x000D_
<div class="slide">something2</div>_x000D_
<div class="slide">something3</div>_x000D_
<div class="slide">something4</div>_x000D_
</div>
_x000D_
You must have either disabled
, froze
or uninstalled
FaceProvider in settings>applications>all
This will only happen if it's frozen
, either uninstall
it, or enable
it.
/^0|[1-9]\d*$/
You are using the pointer newFile
without allocating space for it.
struct stasher_file *newFile = malloc(sizeof(stasher_file));
Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Yes, datepicker supports max date property.
$("#datepickeraddcustomer").datepicker({
dateFormat: "yy-mm-dd",
maxDate: new Date()
});
For inserting a separator:
df$x <- paste(df$n, "-", df$s)
In the majority of cases you would use:
elem != null
Unlike a simple if (elem)
, it allows 0
, false
, NaN
and ''
, but rejects null
or undefined
, making it a good, general test for the presence of an argument, or property of an object.
The other checks are not incorrect either, they just have different uses:
if (elem)
: can be used if elem
is guaranteed to be an object, or if false
, 0
, etc. are considered "default" values (hence equivalent to undefined
or null
).
typeof elem == 'undefined'
can be used in cases where a specified null
has a distinct meaning to an uninitialised variable or property.
elem
is not declared (i.e. no var
statement, not a property of window
, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.Also useful is a strict comparison against undefined
:
if (elem === undefined) ...
However, because the global undefined
can be overridden with another value, it is best to declare the variable undefined
in the current scope before using it:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
A secondary advantage of this method is that JS minifiers can reduce the undefined
variable to a single character, saving you a few bytes every time.
In the neural network terminology:
Example: if you have 1000 training examples, and your batch size is 500, then it will take 2 iterations to complete 1 epoch.
FYI: Tradeoff batch size vs. number of iterations to train a neural network
The term "batch" is ambiguous: some people use it to designate the entire training set, and some people use it to refer to the number of training examples in one forward/backward pass (as I did in this answer). To avoid that ambiguity and make clear that batch corresponds to the number of training examples in one forward/backward pass, one can use the term mini-batch.
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
Actually you need to change your read
to read -r
which will make it ignore backslashes.
Also, you should escape quotes and backslashes. So
while read -r line; do
line="${line//\\/\\\\}"
line="${line//\"/\\\"}"
line="${line//\`/\\\`}"
eval echo "\"$line\""
done > destination.txt < source.txt
Still a terrible way to do expansion though.
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
May be beating a dead horse here, but I bench-marked the cursor for loop, and that performed about as well as the no_data_found method:
declare
otherVar number;
begin
for i in 1 .. 5000 loop
begin
for foo_rec in (select NEEDED_FIELD from t where cond = 0) loop
otherVar := foo_rec.NEEDED_FIELD;
end loop;
otherVar := 0;
end;
end loop;
end;
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.18
My function checks if number is +ve and could be have decimal value as well.
function validateNumeric(numValue){
var value = parseFloat(numValue);
if (!numValue.toString().match(/^[-]?\d*\.?\d*$/))
return false;
else if (numValue < 0) {
return false;
}
return true;
}
You mean something like this?
<div class="image123">
<div class="imgContainer">
<img src="/images/tv.gif" height="200" width="200"/>
<p>This is image 1</p>
</div>
<div class="imgContainer">
<img class="middle-img" src="/images/tv.gif"/ height="200" width="200"/>
<p>This is image 2</p>
</div>
<div class="imgContainer">
<img src="/images/tv.gif"/ height="200" width="200"/>
<p>This is image 3</p>
</div>
</div>
with the imgContainer style as
.imgContainer{
float:left;
}
Also see this jsfiddle.
By Using map
var values = $("input[name='pname[]']")
.map(function(){return $(this).val();}).get();
This answer maybe late but I just happened to fix the issue. Here is my c_cpp_properties.json file:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/c++/5.4.0/",
"usr/local/include/",
"usr/include/"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++14",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}


is the HTML representation in hex of a line feed
character. It represents a new line on Unix and Unix-like (for example) operating systems.
You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
If you're willing to use a Volume and a ConfigMap, you can mount ConfigMap data as a script, and then run that script:
---
apiVersion: v1
kind: ConfigMap
metadata:
name: my-configmap
data:
entrypoint.sh: |-
#!/bin/bash
echo "Do this"
echo "Do that"
---
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: "ubuntu:14.04"
command:
- /bin/entrypoint.sh
volumeMounts:
- name: configmap-volume
mountPath: /bin/entrypoint.sh
readOnly: true
subPath: entrypoint.sh
volumes:
- name: configmap-volume
configMap:
defaultMode: 0700
name: my-configmap
This cleans up your pod spec a little and allows for more complex scripting.
$ kubectl logs my-pod
Do this
Do that
The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.
One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.
This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.
If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file.
And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.
If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.
I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.
Here's one application that works for me. In our case...I wanted the Sales team to use SVN for certain docs (Price sheets and such)...but a bit over there head.
I setup an Auto SVN like this: - Created a REPO in my SVN server. - Checked out repo into a DB folder call AutoSVN. - I run EasySVN on my PC, which auto commits and updates the REPO.
With he 'Auto', there are no log comments, but not critical for these particular docs.
The Sales guys use the DB folder...and simply maintain the file name of those docs that need version control such as price sheets.
So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.
The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.
This helped me change my code, and I now have it working. - Thanks for your comments.
My implementation ended up looking like this;
I require my routes in the app.js:
var express = require('express')
, site = require('./site')
, wiki = require('./wiki');
And I add my routes like this:
app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);
I have two files called wiki.js and site.js in the root of my app, containing this:
exports.edit = function(req, res) {
var wiki_entry = req.params.id;
res.render('wiki/edit', {
title: 'Editing Wiki',
wiki: wiki_entry
})
}
if myfile.closed == False:
print("File is still open ################")
You may also want to cut the data frame into an arbitrary number of smaller dataframes. Here, we cut into two dataframes.
x = data.frame(num = 1:26, let = letters, LET = LETTERS)
set.seed(10)
split(x, sample(rep(1:2, 13)))
gives
$`1`
num let LET
3 3 c C
6 6 f F
10 10 j J
12 12 l L
14 14 n N
15 15 o O
17 17 q Q
18 18 r R
20 20 t T
21 21 u U
22 22 v V
23 23 w W
26 26 z Z
$`2`
num let LET
1 1 a A
2 2 b B
4 4 d D
5 5 e E
7 7 g G
8 8 h H
9 9 i I
11 11 k K
13 13 m M
16 16 p P
19 19 s S
24 24 x X
25 25 y Y
You can also split a data frame based upon an existing column. For example, to create three data frames based on the cyl
column in mtcars
:
split(mtcars,mtcars$cyl)
I usually just add the following custom CSS, the W3School example prepended with cursor-
.cursor-alias {cursor: alias;}_x000D_
.cursor-all-scroll {cursor: all-scroll;}_x000D_
.cursor-auto {cursor: auto;}_x000D_
.cursor-cell {cursor: cell;}_x000D_
.cursor-context-menu {cursor: context-menu;}_x000D_
.cursor-col-resize {cursor: col-resize;}_x000D_
.cursor-copy {cursor: copy;}_x000D_
.cursor-crosshair {cursor: crosshair;}_x000D_
.cursor-default {cursor: default;}_x000D_
.cursor-e-resize {cursor: e-resize;}_x000D_
.cursor-ew-resize {cursor: ew-resize;}_x000D_
.cursor-grab {cursor: -webkit-grab; cursor: grab;}_x000D_
.cursor-grabbing {cursor: -webkit-grabbing; cursor: grabbing;}_x000D_
.cursor-help {cursor: help;}_x000D_
.cursor-move {cursor: move;}_x000D_
.cursor-n-resize {cursor: n-resize;}_x000D_
.cursor-ne-resize {cursor: ne-resize;}_x000D_
.cursor-nesw-resize {cursor: nesw-resize;}_x000D_
.cursor-ns-resize {cursor: ns-resize;}_x000D_
.cursor-nw-resize {cursor: nw-resize;}_x000D_
.cursor-nwse-resize {cursor: nwse-resize;}_x000D_
.cursor-no-drop {cursor: no-drop;}_x000D_
.cursor-none {cursor: none;}_x000D_
.cursor-not-allowed {cursor: not-allowed;}_x000D_
.cursor-pointer {cursor: pointer;}_x000D_
.cursor-progress {cursor: progress;}_x000D_
.cursor-row-resize {cursor: row-resize;}_x000D_
.cursor-s-resize {cursor: s-resize;}_x000D_
.cursor-se-resize {cursor: se-resize;}_x000D_
.cursor-sw-resize {cursor: sw-resize;}_x000D_
.cursor-text {cursor: text;}_x000D_
.cursor-w-resize {cursor: w-resize;}_x000D_
.cursor-wait {cursor: wait;}_x000D_
.cursor-zoom-in {cursor: zoom-in;}_x000D_
.cursor-zoom-out {cursor: zoom-out;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<button type="button" class="btn btn-success cursor-pointer">Sample Button</button>
_x000D_
What worked best for me is
scroll_view.post(new Runnable() {
@Override
public void run() {
// This method works but animates the scrolling
// which looks weird on first load
// scroll_view.fullScroll(View.FOCUS_DOWN);
// This method works even better because there are no animations.
scroll_view.scrollTo(0, scroll_view.getBottom());
}
});
I just wrote this helper function. Put it in App_Code/JS.cshtml
:
@using System.Web.Script.Serialization
@helper Encode(object obj)
{
@(new HtmlString(new JavaScriptSerializer().Serialize(obj)));
}
Then in your example, you can do something like this:
var title = @JS.Encode(Model.Title);
Notice how I don't put quotes around it. If the title already contains quotes, it won't explode. Seems to handle dictionaries and anonymous objects nicely too!
This is how i do it
$posts = Post::with(['category' => function($query){
$query->select('id', 'name');
}])->get();
First answer by user2317976 did not work for me, i am using laravel 5.1
This can be helpful:
<input type="text" name="username" value="admin" >
<style type="text/css">
input[name=username] {
pointer-events: none;
}
</style>
Update:
and if want to disable from tab index you can use it this way:
<input type="text" name="username" value="admin" tabindex="-1" >
<style type="text/css">
input[name=username] {
pointer-events: none;
}
</style>
" ".join(foo.split())
is not quite correct with respect to the question asked because it also entirely removes single leading and/or trailing white spaces. So, if they shall also be replaced by 1 blank, you should do something like the following:
" ".join(('*' + foo + '*').split()) [1:-1]
Of course, it's less elegant.
If it's always going to be an even LHS/RHS split, you can also use the partition
method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS)
if the separator is found, and (original_string, '', '')
if the separator wasn't present:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
Submit
is null
because it is not part of activity_main.xml
When you call findViewById
inside an Activity
, it is going to look for a View
inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="@+id/LoginTitle"
but what you want is probably
android:layout_below="@id/LoginTitle"
See this question about the difference between @id
and @+id
.
It works fine oracle
merge into table1 t1
using (select * from table2) t2
on (t1.empid = t2.empid)
when matched then update set t1.salary = t2.salary
I have just fixed using following steps, It may help you.
Step: 1
Step: 2
Step: 3
Step: 4
Step: 5
Then run following query.
ALTER DATABASE YourDBName
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO
Enjoy...!
I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.
Error :
Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at hudson.Proc$LocalProc.<init>(Proc.java:250)
at hudson.Proc$LocalProc.<init>(Proc.java:219)
at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
at hudson.Launcher$ProcStarter.start(Launcher.java:455)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
at hudson.model.Build$BuildExecution.build(Build.java:206)
at hudson.model.Build$BuildExecution.doRun(Build.java:163)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1853)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Solution :
1 - Install Cygwin and note the directory where it gets installed.
It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.
2 - Tell Jenkins where sh.exe is located.
Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.
That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.
you should use position:fixed
to make z-index
values to apply to your div
In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:
Dim query As String
Dim newRow As Long ' note change of data type
Dim db As DAO.Database
query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
Set db = CurrentDB
db.Execute(query)
newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
Set db = Nothing
I used to do INSERTs by opening an AddOnly
recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO
.
See question: How to find an item in a std::vector?
You'll also need to ensure you've implemented a suitable operator==()
for your object, if the default one isn't sufficient for a "deep" equality test.
The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...
Here's the most important part from the lecture notes of CS299 (by Andrew Ng) related to the topic, which really helps me understand the difference between discriminative and generative learning algorithms.
Suppose we have two classes of animals, elephant (y = 1
) and dog (y = 0
). And x is the feature vector of the animals.
Given a training set, an algorithm like logistic regression or the perceptron algorithm (basically) tries to find a straight line — that is, a decision boundary — that separates the elephants and dogs. Then, to classify a new animal as either an elephant or a dog, it checks on which side of the decision boundary it falls, and makes its prediction accordingly. We call these discriminative learning algorithm.
Here's a different approach. First, looking at elephants, we can build a model of what elephants look like. Then, looking at dogs, we can build a separate model of what dogs look like. Finally, to classify a new animal, we can match the new animal against the elephant model, and match it against the dog model, to see whether the new animal looks more like the elephants or more like the dogs we had seen in the training set. We call these generative learning algorithm.
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
In Eclipse go to Help
Install New Software
---> Add
inside Add Repository write the Name: ADT
(or whatever you want)
Location: https://dl-ssl.google.com/android/eclipse/
after loading you should get Developer Tools and NDK Plugins
check both if you want to use the Native Developer Kit (NDK) in the future or check
Developer Tool only
click Next
Finish
In build:app
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.proyecto.marketdillo"
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0-rc02'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-firestore:17.1.5'
implementation 'com.android.support:multidex:1.0.3'
}
apply plugin: 'com.google.gms.google-services'
Stopwatch is designed for this purpose and is one of the best way to measure execution time in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTimes to measure execution time in .NET.
Your installation is wrong; you are using a very old compiler version (1.0.3.0).
tsc --version
should return a version of 2.5.2.
Check where that old compiler is located using: which tsc
(or where tsc
) and remove it.
Try uninstalling the "global" typescript
npm uninstall -g typescript
Installing as part of a local dev dependency of your project
npm install typescript --save-dev
Execute it from the root of your project
./node_modules/.bin/tsc
1. In my opinion, the most convenient way is to search for one
occurrence first, and then invoke the following :substitute
command:
:%s///gc
Since the pattern is empty, this :substitute
command will look for
the occurrences of the last-used search pattern, and will then replace
them with the empty string, each time asking for user confirmation,
realizing exactly the desired behavior.
2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.
vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
if search(@/, 'bcW')
norm! v
call search(@/, 'ceW')
else
norm! gv
endif
endfunction
Using these mappings one can delete the match under the cursor with
di/
, or apply any other operator or visually select it with vi/
.
With Spring OAuth 2.0.7-RELEASE the following command works for me
curl -v -u [email protected]:12345678 -d "grant_type=client_credentials" http://localhost:9999/uaa/oauth/token
It works with Chrome POSTMAN too, just make sure you client and secret in "Basic Auth" tab, set method to "POST" and add grant type in "form data" tab.
Start monogdb service using
sudo service mongod start
then from the new window or terminal start mongo client using
mongo
As you point 499
a connection abortion logged by the nginx. But usually this is produced when your backend server is being too slow, and another proxy timeouts first or the user software aborts the connection. So check if uWSGI is answering fast or not of if there is any load on uWSGI / Database server.
In many cases there are some other proxies between the user and nginx. Some can be in your infrastructure like maybe a CDN, Load Balacer, a Varnish cache etc. Others can be in user side like a caching proxy etc.
If there are proxies on your side like a LoadBalancer / CDN ... you should set the timeouts to timeout first your backend and progressively the other proxies to the user.
If you have:
user >>> CDN >>> Load Balancer >>> Nginx >>> uWSGI
I'll recommend you to set:
n
seconds to uWSGI timeoutn+1
seconds to nginx timeoutn+2
senconds to timeout to Load Balancern+3
seconds of timeout to the CDN.If you can't set some of the timeouts (like CDN) find whats is its timeout and adjust the others according to it (n
, n-1
...).
This provides a correct chain of timeouts. and you'll find really whose giving the timeout and return the right response code to the user.
I encounter same problem when I setup tomcat and mysql server on VirtualBox VM using chef.
in this case, I think true problem is VirtualBox seems to assign non-localhost address to eth0 like
[vagrant@localhost webapps]$ /sbin/ifconfig
eth0 Link encap:Ethernet HWaddr 08:00:27:60:FC:47
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
then auto-detection feature of chef's recipe using 10.0.2.15 as mysql server bind address.
so specify bind address for node params of chef's recipe solve problem in my case. I hope this information helps people using chef with vagrant.
{
"name" : "db",
"default_attributes" : {
"mysql" : {
"bind_address" : "localhost"
...
}
git --work-tree=/tmp/files_without_dot_git clone --depth=1 \
https://git.yourgit.your.com/myawesomerepo.git \
/tmp/deleteme_contents_of_dot_git
Both the directories in /tmp are created on the fly. No need to pre-create these.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
I wrote a generic solution in C# loosely based on @Mehrdad Afshari answer:
void Example(List<MyObject> actualObjects)
{
List<TreeNode<MyObject>> treeRoots = actualObjects.BuildTree(obj => obj.ID, obj => obj.ParentID, -1);
}
public class TreeNode<T>
{
public TreeNode(T value)
{
Value = value;
Children = new List<TreeNode<T>>();
}
public T Value { get; private set; }
public List<TreeNode<T>> Children { get; private set; }
}
public static class TreeExtensions
{
public static List<TreeNode<TValue>> BuildTree<TKey, TValue>(this IEnumerable<TValue> objects, Func<TValue, TKey> keySelector, Func<TValue, TKey> parentKeySelector, TKey defaultKey = default(TKey))
{
var roots = new List<TreeNode<TValue>>();
var allNodes = objects.Select(overrideValue => new TreeNode<TValue>(overrideValue)).ToArray();
var nodesByRowId = allNodes.ToDictionary(node => keySelector(node.Value));
foreach (var currentNode in allNodes)
{
TKey parentKey = parentKeySelector(currentNode.Value);
if (Equals(parentKey, defaultKey))
{
roots.Add(currentNode);
}
else
{
nodesByRowId[parentKey].Children.Add(currentNode);
}
}
return roots;
}
}
The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.
Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""
Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.
<!doctype html>
<!-- saved from url=(0014)about:internet -->
<html>
<title>Ikariam Autologin</title>
</head>
<body>
<form id="loginForm" name="loginForm" method="post" action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
<select name="uni_url" id="logServer" class="validate[required]">
<option class="" value="s666.en.ikariam.com" fbUrl="" cookieName="" >
Test_en
</option>
</select>
<input id="loginName" name="name" type="text" value="PlayersName" class="" />
<input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
<input type="hidden" id="loginKid" name="kid" value=""/>
</form>
<script>document.loginForm.submit();</script>
</body></html>
Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.
Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
Those files are created and used by Android Studio editor.
You don't need to check in those files to version control.
Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.
Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.
Final keyword in C++ when added to a function, prevents it from being overridden by a base class. Also when added to a class prevents inheritance of any type. Consider the following example which shows use of final specifier. This program fails in compilation.
#include <iostream>
using namespace std;
class Base
{
public:
virtual void myfun() final
{
cout << "myfun() in Base";
}
};
class Derived : public Base
{
void myfun()
{
cout << "myfun() in Derived\n";
}
};
int main()
{
Derived d;
Base &b = d;
b.myfun();
return 0;
}
Also:
#include <iostream>
class Base final
{
};
class Derived : public Base
{
};
int main()
{
Derived d;
return 0;
}
When signing into the server to execute the code use this instead:
ssh -X username@servername
the -X
will get rid of the no display name and no $DISPLAY environment variable
error
:)
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
I've implemented what I could gather from a few of these. This works in Windows, and since this is a community wiki, I figure I would share my code as well:
class Command(threading.Thread):
def __init__(self, cmd, outFile, errFile, timeout):
threading.Thread.__init__(self)
self.cmd = cmd
self.process = None
self.outFile = outFile
self.errFile = errFile
self.timed_out = False
self.timeout = timeout
def run(self):
self.process = subprocess.Popen(self.cmd, stdout = self.outFile, \
stderr = self.errFile)
while (self.process.poll() is None and self.timeout > 0):
time.sleep(1)
self.timeout -= 1
if not self.timeout > 0:
self.process.terminate()
self.timed_out = True
else:
self.timed_out = False
Then from another class or file:
outFile = tempfile.SpooledTemporaryFile()
errFile = tempfile.SpooledTemporaryFile()
executor = command.Command(c, outFile, errFile, timeout)
executor.daemon = True
executor.start()
executor.join()
if executor.timed_out:
out = 'timed out'
else:
outFile.seek(0)
errFile.seek(0)
out = outFile.read()
err = errFile.read()
outFile.close()
errFile.close()
using ".intValue()" on BigDecimal object is not right when you want to check if its grater than zero. The only option left is ".compareTo()" method.
SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;
OR
SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;
both results will same....
You can also consult readlink -f "which java
". However it might not work for all binary wrappers. It is most likely better to actually start a Java class.
I was using jruby, in my case I created under config/initializers
postgres_driver.rb
$CLASSPATH << '~/.rbenv/versions/jruby-1.7.17/lib/ruby/gems/shared/gems/jdbc-postgres-9.4.1200/lib/postgresql-9.4-1200.jdbc4.jar'
or wherever your driver is, and that's it !
This code is perfectly working for me.
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
[label setFont:[UIFont systemFontOfSize:11]];
Why don't you create OleDbConnection? There are a lot of available resources in the Internet. Here is an example
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filename+";Extended Properties=Excel 8.0");
con.Open();
try
{
//Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference
DataSet myDataSet = new DataSet();
OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM ["+listname+"$]" , con);
myCommand.Fill(myDataSet);
con.Close();
richTextBox1.AppendText("\nDataSet Filled");
//Travers through each row in the dataset
foreach (DataRow myDataRow in myDataSet.Tables[0].Rows)
{
//Stores info in Datarow into an array
Object[] cells = myDataRow.ItemArray;
//Traverse through each array and put into object cellContent as type Object
//Using Object as for some reason the Dataset reads some blank value which
//causes a hissy fit when trying to read. By using object I can convert to
//String at a later point.
foreach (object cellContent in cells)
{
//Convert object cellContect into String to read whilst replacing Line Breaks with a defined character
string cellText = cellContent.ToString();
cellText = cellText.Replace("\n", "|");
//Read the string and put into Array of characters chars
richTextBox1.AppendText("\n"+cellText);
}
}
//Thread.Sleep(15000);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
//Thread.Sleep(15000);
}
finally
{
con.Close();
}
This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below
@Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);
"Not Possible". You can do this using this query. Initialize here
declare @sql nvarchar(4000)=''
Set Value & exec command of your sp with parameters
SET @sql += ' Exec spName @param'
EXECUTE sp_executesql @sql, N'@param type', @param = @param
From the Document "Mastering the VI editor":
number (nu)
Displays lines with line numbers on the left side.
The solution for preventing Google Chrome error messages on input each symbol:
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>_x000D_
<form method="post" action="#">_x000D_
<label for="text_number_1">Here you will see browser's error validation message on input:</label><br>_x000D_
<input id="test_number_1" type="number" min="0" required="true"_x000D_
oninput="this.setCustomValidity('')"_x000D_
oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
<input type="submit"/>_x000D_
</form>_x000D_
_x000D_
<form method="post" action="#">_x000D_
<p></p>_x000D_
<label for="text_number_1">Here you will see no error messages on input:</label><br>_x000D_
<input id="test_number_2" type="number" min="0" required="true"_x000D_
oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"_x000D_
oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
<input type="submit"/>_x000D_
</form>
_x000D_
Shamelessly copied from Generic deserialization of an xml string
public static T DeserializeFromXmlString<T>(string xmlString)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlString))
{
return (T) serializer.Deserialize(reader);
}
}
I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)
That should answer your question.
Here it is:
From your first script, call your second script with the following line:
wscript.exe invis.vbs run.bat %*
Actually, you are calling a vbs script with:
%*
)Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:
See the question for the full invis.vbs script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
^
means "invisible window" ---|
Update after Tammen's feedback:
If you are in a DOS session and you want to launch another script "in the background", a simple /b
(as detailed in the same aforementioned question) can be enough:
You can use
start /b second.bat
to launch a second batch file asynchronously from your first that shares your first one's window.
You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon. Hope this help.
To set an icon of a shortcut programmatically, see this article using SetIconLocation
:
How Can I Change the Icon for an Existing Shortcut?:
https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/
Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save
After years I have discovered one, if not the, answer to the Microsoft bug of the 'User-defined type not defined' error in Excel. I'm running Excel 2010 for Windows.
If you have a UDF named for example 'xyz()
', then if you invoke a non-existent entity beginning with that name followed by a period followed by other chars -- e.g., if you try to invoke non-existent range name 'xyz.abc
', the stupid app throws that wrong msg., after which it returns you to your sheet.
In my case it was especially unnerving, because I have UDFs named with just one letter, e.g. x()
, y()
, etc., and I also have range names that include periods--'x.a
', 'c.d
', etc. Every time I, say, misspelled a range name--for example, 'x.h', the 'User-defined …' error was thrown simply because a UDF named 'x()
' existed somewhere in my project.
It took several hrs. to diagnose. Suggestions above to incrementally remove code from your project, or conversely strip all code and incrementally add it back in, were on the right track but they didn't follow thru. It has nothing to do with code per se; it has only to do with the name of the first line of code in each proc, namely the Sub MyProc
or Function MyProc
line naming the proc. It was when I commented out one of my 1-letter-named UDFs in a completely unrelated part of the project that the bugged error msg. went away, and from there, after another hr. or so, I was able to generalize the rule as stated.
Perhaps the bug also occurs with punctuation characters other than period ('.
') But there aren't very many non-alpha chars permitted in a range name; underline ('_
') is allowed, but using it in the manner described doesn't seem to throw the bug.
Jim Luedke
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:
When you add the Scriptler build step into your job, select the option "Define script parameters"
Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.
In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:
println "JOB_NAME = $JOB_NAME"
I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!
To solve this issue, I pasted my layout into https://www.xmlvalidation.com/, which told me exactly what the error was. As was the case with other answers, my XML had <
in a string.
you will need to convert given string to JSONObject
instead of JSONArray
because current String contain JsonObject
as root element instead of JsonArray
:
JSONObject jsonObject = new JSONObject(readlocationFeed);
I think this is no longer an issue in Chrome but just in case. I wrote this jQuery script to inspect the DOM when I move around with the TAB key.
If changed to use 'mouseover', would look like this:
$("body *").on('mouseover', function(event) {
console.log(event.target);
inspect(event.target);
event.stopPropagation();
});
You can easily modify it to remove the event handler whenever you click or do something on an element you want to stop at.
Even using stack will not convert a recursive algorithm into iterative. Normal recursion is function based recursion and if we use stack then it becomes stack based recursion. But its still recursion.
For recursive algorithms, space complexity is O(N) and time complexity is O(N). For iterative algorithms, space complexity is O(1) and time complexity is O(N).
But if we use stack things in terms of complexity remains same. I think only tail recursion can be converted into iteration.
Suppose,
let a = 123456
First we will convert it into string and then apply split to convert it into array of characters and then map over it to convert the array to integer.
let b = a.toString().split('').map(val=>parseInt(val))
console.log(b)
I met this issue this morning because I used the same executable in DIFFERENT OSes: after compiling my program with gcc -ggdb -Wall test.c -o test
in my Mac(10.15.2), I ran gdb
with the executable in Ubuntu(16.04) in my VirtualBox.
Fix: recompile with the same command under Ubuntu, then you should be good.
Since 
(html) is 0D
(hex), this can be represented as '\u000d'
str = str.replace(/\n/g, '\u000d');
Sharing with you guys an AngularJS filter that replaces \n
with that character thanks to the references in the other answers
app.filter('titleLineBreaker', function () {
return function (str) {
if (!str) {
return str;
}
return str.replace(/\n/g, '\u000d');
};
});
usage
<div title="{{ message | titleLineBreaker }}"> </div>
absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!
You can instantiate an anonymous class and then test that class.
public class ClassUnderTest_Test {
private ClassUnderTest classUnderTest;
private MyDependencyService myDependencyService;
@Before
public void setUp() throws Exception {
this.myDependencyService = new MyDependencyService();
this.classUnderTest = getInstance();
}
private ClassUnderTest getInstance() {
return new ClassUnderTest() {
private ClassUnderTest init(
MyDependencyService myDependencyService
) {
this.myDependencyService = myDependencyService;
return this;
}
@Override
protected void myMethodToTest() {
return super.myMethodToTest();
}
}.init(myDependencyService);
}
}
Keep in mind that the visibility must be protected
for the property myDependencyService
of the abstract class ClassUnderTest
.
You can also combine this approach neatly with Mockito. See here.
You probably need to do a git stash
before you git pull
, this is because it is reading your old config file. So do:
git stash
git pull
git commit -am <"say first commit">
git push
Also see git-stash(1) Manual Page.
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
OK Here is a Good And Proper Solution
You have a Div call with an id="myDiv"
so the function goes.
function GetScrollerEndPoint()
{
var scrollHeight = $("#myDiv").prop('scrollHeight');
var divHeight = $("#myDiv").height();
var scrollerEndPoint = scrollHeight - divHeight;
var divScrollerTop = $("#myDiv").scrollTop();
if(divScrollerTop === scrollerEndPoint)
{
//Your Code
//The Div scroller has reached the bottom
}
}
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
The question of speed is irrelevant without a specific speed problem.
If you are writing SQL code to make a change to an existing row, you UPDATE it. Anything else is incorrect.
If you're going to break the rules of how code should work, then you'd better have a damn good, quantified reason for it, and not a vague idea of "This way is faster", when you don't have any idea what "faster" is.
$('#StartButton:disabled') ..
Then check if it's undefined.
Collections class has an efficient method for shuffling, that can be copied, so as not to depend on it:
/**
* Usage:
* int[] array = {1, 2, 3};
* Util.shuffle(array);
*/
public class Util {
private static Random random;
/**
* Code from method java.util.Collections.shuffle();
*/
public static void shuffle(int[] array) {
if (random == null) random = new Random();
int count = array.length;
for (int i = count; i > 1; i--) {
swap(array, i - 1, random.nextInt(i));
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
just try this, it works fine in my browser:
your response writing code should be
Response.Write("<script>alert('login successful');</script>");
Hope this works
For future reference to people who come here. after you run the command that was given in the third answer here(I am using now Laravel 5.3).
php artisan config:cache
You may encounter this problem:
[ReflectionException]
Class view does not exist
In that case, you need to add it back manually to your provider list under the app.php file. GO-TO:
app->config->app.php->'providers[]'
and add it, like so:
Illuminate\View\ViewServiceProvider::class,
Hope That helps someone.
use trim() method of javascript after all angularjs is also a javascript framework and it is not necessary to put $ to apply trim()
for example
var x="hello world";
x=x.trim()
I know I'm coming at this years later, but I can't believe no one suggested usermod.
usermod --password `perl -e "print crypt('password','sa');"` root
Hell, just in case someone wants to do this on an older HPUX you can use usermod.sam
.
/usr/sam/lbin/usermod.sam -F -p `perl -e "print crypt('password','sa');"` username
The -F is only needed if the person executing the script is the current user. Of course you don't need to use Perl to create the hash. You could use openssl or many other commands in its place.
EXP (export) and IMP (import) are the two tools you need. It's is better to try to run these on the command line and on the same machine.
It can be run from remote, you just need to setup you TNSNAMES.ORA
correctly and install all the developer tools with the same version as the database. Without knowing the error message you are experiencing then I can't help you to get exp/imp to work.
The command to export a single user:
exp userid=dba/dbapassword OWNER=username DIRECT=Y FILE=filename.dmp
This will create the export dump file.
To import the dump file into a different user schema, first create the newuser in SQLPLUS:
SQL> create user newuser identified by 'password' quota unlimited users;
Then import the data:
imp userid=dba/dbapassword FILE=filename.dmp FROMUSER=username TOUSER=newusername
If there is a lot of data then investigate increasing the BUFFERS
or look into expdp/impdp
Most common errors for exp and imp are setup. Check your PATH
includes $ORACLE_HOME/bin
, check $ORACLE_HOME
is set correctly and check $ORACLE_SID
is set
This can be done without regex
which is more efficient:
var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);
And as a bonus, it also stores the number, which may be useful to some people.
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
First of all you should configure $resource
in different manner: without query params in the URL. Default query parameters may be passed as properties of the second parameter in resource(url, paramDefaults, actions)
. It is also to be mentioned that you configure get
method of resource and using query
instead.
Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource(
'../rest/api.php',
{ method: 'getTask', q: '*' }, // Query parameters
{'query': { method: 'GET' }}
);
})
Documentation
select * from tbl where col like 'ABC%'
or col like 'XYZ%'
or col like 'PQR%';
This works in toad and powerbuilder. Don't know about the rest
If you are still looking for an answer, try checking this question thread. It helped me resolve a similar problem.
edit:
The solution that helped me was to run Update-Package Microsoft.AspNet.WebApi -reinstall
from the NugGet package manager, as suggested by Pathoschild.
I then had to delete my .suo file and restart VS, as suggested by Sergey Osypchuk in this thread.
An answer that I've been using that has been working for me quite well that I didn't already see here (this question is very old, so it may have not worked then) is actually
SELECT t.phone,
t.phone2
FROM jewishyellow.users t
WHERE t.phone LIKE '813%'
AND t.phone2 > ''
Notice the > ''
part, which will check if the value is not null, and if the value isn't just whitespace or blank.
Basically, if the field has something in it other than whitespace or NULL
, it is true. It's also super short, so it's easy to write, and another plus over the COALESCE()
and IFNULL()
functions is that this is index friendly, since you're not comparing the output of a function on a field to anything.
Test cases:
SELECT if(NULL > '','true','false');-- false
SELECT if('' > '','true','false');-- false
SELECT if(' ' > '','true','false');-- false
SELECT if('\n' > '','true','false');-- false
SELECT if('\t' > '','true','false');-- false
SELECT if('Yeet' > '','true','false');-- true
UPDATE There is a caveat to this that I didn't expect, but numerical values that are zero or below are not greater than a blank string, so if you're dealing with numbers that can be zero or negative then DO NOT DO THIS, it bit me very recently and was very difficult to debug :(
If you're using strings (char, varchar, text, etc.), then this will be perfectly be fine, just be careful with numerics.
ObjectID
s are objects so if you just compare them with ==
you're comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
range(x,y)
returns a list of each number in between x and y if you use a for
loop, then range
is slower. In fact, range
has a bigger Index range. range(x.y)
will print out a list of all the numbers in between x and y
xrange(x,y)
returns xrange(x,y)
but if you used a for
loop, then xrange
is faster. xrange
has a smaller Index range. xrange
will not only print out xrange(x,y)
but it will still keep all the numbers that are in it.
[In] range(1,10)
[Out] [1, 2, 3, 4, 5, 6, 7, 8, 9]
[In] xrange(1,10)
[Out] xrange(1,10)
If you use a for
loop, then it would work
[In] for i in range(1,10):
print i
[Out] 1
2
3
4
5
6
7
8
9
[In] for i in xrange(1,10):
print i
[Out] 1
2
3
4
5
6
7
8
9
There isn't much difference when using loops, though there is a difference when just printing it!
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
one more if you want to switch IE 8 page render in IE 8 standard mode
<meta http-equiv="X-UA-Compatible" content="IE=100" /> <!-- IE8 mode -->
If you're encountering this in Jupyter/Jupyerlab while trying to pip install foo
, you can sometimes work around it by using !python -m pip install foo
instead.
As my purpose is to get an empty version of the test database to import data from an external previous current active source (Access database) once all is fine tuned. I found that using DBCC CloneDatabase with Verify_CloneDB option fits perfectly.
bool === tool ? bool : tool
if you want the value to hold true if tool
(another boolean) has the same value