You have to realize that server-side sessions are an artificial add-on to HTTP. Since HTTP is stateless, the server needs to somehow recognize that a request belongs to a particular user it knows and has a session for. There are 2 ways to do this:
What are you trying to do anyway? Why would you want tabs to have separate sessions? Maybe there's a way to achieve your goal without using sessions at all?
Edit: For testing, other solutions can be found (such as running several browser instances on separate VMs). If one user needs to act in different roles at the same time, then the "role" concept should be handled in the app so that one login can have several roles. You'll have to decide whether this, using URL rewriting, or just living with the current situation is more acceptable, because it's simply not possible to handle browser tabs separately with cookie-based sessions.
Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:
if (HttpContext.Current.Response.Cookies.Count > 0)
{
foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
{
HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
}
}
}
Set objFSO=CreateObject("Scripting.FileSystemObject")
' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close
'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
Wscript.Echo strLine
Loop
objFile.Close
'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
I also had the same problem, as a quick workaround, I used blend to determine how much padding was being added. In my case it was 12, so I used a negative margin to get rid of it. Now everything can now be centered properly
My first thought was to write a single query, but you said that was not possible because one is run by the user and the other is run in the background. How are you storing the list of ids to pass from the user to the background process? Why not put them in a temporary table with a column to signify the order.
So how about this:
It looks like people answered the first part of your question (use application/json).
For the second part: It is perfectly legal to send query parameters in a HTTP POST Request.
Example:
POST /members?id=1234 HTTP/1.1
Host: www.example.com
Content-Type: application/json
{"email":"[email protected]"}
Query parameters are commonly used in a POST request to refer to an existing resource. The above example would update the email address of an existing member with the id of 1234.
You can use rebase, for instance, git rebase our-team
when you are on your branch featurex
It will move the start point of the branch at the end of your our-team
branch, merging all changes in your featurex
branch.
Here I have my example which works just fine:
declare
ex number;
begin
select MAX(MAX_FK_ID) + 1 into ex from TABLE;
If ex > 0 then
begin
execute immediate 'DROP SEQUENCE SQ_NAME';
exception when others then
null;
end;
execute immediate 'CREATE SEQUENCE SQ_NAME INCREMENT BY 1 START WITH ' || ex || ' NOCYCLE CACHE 20 NOORDER';
end if;
end;
You need to shift and mask the value, so for example...
If you want to read the first two bits, you just need to mask them off like so:
int value = input & 0x3;
If you want to offset it you need to shift right N bits and then mask off the bits you want:
int value = (intput >> 1) & 0x3;
To read three bits like you asked in your question.
int value = (input >> 1) & 0x7;
A simple and supported version is Daemonize
.
Install it from Python Package Index (PyPI):
$ pip install daemonize
and then use like:
...
import os, sys
from daemonize import Daemonize
...
def main()
# your code here
if __name__ == '__main__':
myname=os.path.basename(sys.argv[0])
pidfile='/tmp/%s' % myname # any name
daemon = Daemonize(app=myname,pid=pidfile, action=main)
daemon.start()
you have to make a custom object where you used a UIView
and inside you put a UIImageView
and a UILabel
SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.
I prefer this command ll -sha
.
To achieve this just use an Intent using the constant ACTION_SETTINGS, specifically defined to show the System Settings:
startActivity(new Intent(Settings.ACTION_SETTINGS));
startActivityForResult() is optional, only if you want to return some data when the settings activity is closed.
startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);
here you can find a list of contants to show specific settings or details of an aplication.
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
MVC 5.1 and higher solution (will merge local HtmlAttributes and defined in the EditorTemplates):
Shared\EditorTemplates\String.cshtml:
@Html.TextBoxFor(model => model, new { @class = "form-control", placeholder = ViewData.ModelMetadata.Watermark }.ToExpando().MergeHtmlAttributes(ViewData["htmlAttributes"].ToExpando()))
Extensions:
public static IDictionary<string, object> MergeHtmlAttributes(this ExpandoObject source1, dynamic source2)
{
Condition.Requires(source1, "source1").IsNotNull().IsLongerThan(0);
IDictionary<string, object> result = source2 == null
? new Dictionary<string, object>()
: (IDictionary<string, object>) source2;
var dictionary1 = (IDictionary<string, object>) source1;
string[] commonKeys = result.Keys.Where(dictionary1.ContainsKey).ToArray();
foreach (var key in commonKeys)
{
result[key] = string.Format("{0} {1}", dictionary1[key], result[key]);
}
foreach (var item in dictionary1.Where(pair => !result.ContainsKey(pair.Key)))
{
result.Add(item);
}
return result;
}
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
public static bool HasProperty(this ExpandoObject expando, string key)
{
return ((IDictionary<string, object>)expando).ContainsKey(key);
}
Usage:
@Html.EditorFor(m => m.PromotionalCode, new { htmlAttributes = new { ng_model = "roomCtrl.searchRoomModel().promoCode" }})
List<string> l = new List<string> { "@bob.com", "@tom.com" };
List<string> l2 = new List<string> { "[email protected]", "[email protected]" };
List<string> myboblist= (l2.Where (i=>i.Contains("bob")).ToList<string>());
foreach (var bob in myboblist)
Console.WriteLine(bob.ToString());
Try the following:
for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done
The $(( ))
syntax does an arithmetic evaluation of the contents.
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
A class with a field:
Public Class MyStudent
Public StudentId As Integer
The constructor:
Public Sub New(newStudentId As Integer)
StudentId = newStudentId
End Sub
End Class
Do not we have an app which can stream the digital movie from iOS devices like iPhone or iPad to be played on a high definition LED or Plasma TV?
I know of an app air video server which can be used to display content played on computer or laptop on iOS device. But is there any app that can do the reverse & play the digital content from iphone to LED tv .
$(selector).change()
Longer slower alternative, better for abstraction.
$(selector).trigger("change")
You can install the Active Directory snap-in with Powershell on Windows Server 2012 using the following command:
Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools
This helped me when I had problems with the Features screen due to AppFabric and Windows Update errors.
Yahoo has a tutorial on making calls to their REST services using PHP:
Make Yahoo! Web Service REST Calls with PHP
I have not used it myself, but Yahoo is Yahoo and should guarantee for at least some level of quality. They don't seem to cover PUT and DELETE requests, though.
Also, the User Contributed Notes to curl_exec() and others contain lots of good information.
I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.
Assuming your data is in ColumnA:C
and has column labels in Row 1, also that Month is formatted mmm
(this last for ease of sorting):
D2
=IF(AND(A2=A1,C2=C1),D1+1,1)
(One way to deal with what is the tricky issue of multiple entries for the same person for the same month).A1:D(last occupied row no.)
F1
.I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.
L1
.L1
and shift down.L1
.ColumnL
, select Row Labels
and numeric values.L2:L(last selected cell)
Happy to explain further/try again (I've not really tested this) if does not suit.
EDIT (To avoid second block of steps above and facilitate updating for source data changes)
.0. Before first step 2. add a blank row at the very top and move A2:D2
up.
.2. Adjust cell references accordingly (in D3
=IF(AND(A3=A2,C3=C2),D2+1,1)
.
.3. Create pivot table from A:D
.6. Overwrite Row Labels
with Name
.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1
, ColumnG
and rows and columns that show (blank)
.
Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).
Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank)
into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.
Make it a background image that is centered.
.wrapper {background:transparent url(yourimage.jpg) no-repeat center center;}
<div class="wrapper">
...input boxes and labels and submit button here
</div>
When you want your include to know what file it is in (ie. what script name was actually requested), use:
basename($_SERVER["SCRIPT_FILENAME"], '.php')
Because when you are writing to a file you usually know its name.
Edit: As noted by Alec Teal, if you use symlinks it will show the symlink name instead.
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
You can get a client
with new session directly like below.
s3_client = boto3.client('s3',
aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
region_name=REGION_NAME
)
Try just clearing the data (not the entire table including headers):
ACell.ListObject.DataBodyRange.ClearContents
You should put a padding in each object. For example, you want a space between images, you can use the following:
img{
padding: 5px;
}
That means 5px paddin for ALL sides. Read more at http://www.w3schools.com/css/css_padding.asp. By the way, studying a lot before attempting to program will make things easier for you (and for us).
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
ALTER TABLE tablename MODIFY columnname INTEGER;
This will change the datatype of given column
Depending on how many columns you wish to modify it might be best to generate a script, or use some kind of mysql client GUI
Have a look at this article, it's not an exact match to your problem, but suits it:
If (theChar >= '0' && theChar <='9')
it's a digit. You get the idea.
In res/color
place a file "text_selector.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/blue" android:state_focused="true" />
<item android:color="@color/blue" android:state_selected="true" />
<item android:color="@color/green" />
</selector>
Then in TextView
use it:
<TextView
android:id="@+id/value_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text"
android:textColor="@color/text_selector"
android:textSize="15sp"
/>
And in code you'll need to set a click listener.
private var isPressed = false
private fun TextView.setListener() {
this.setOnClickListener { v ->
run {
if (isPressed) {
v.isSelected = false
v.clearFocus()
} else {
v.isSelected = true
v.requestFocus()
}
isPressed = !isPressed
}
}
}
override fun onResume() {
super.onResume()
textView.setListener()
}
override fun onPause() {
textView.setOnClickListener(null)
super.onPause()
}
Sorry if there are errors, I changed a code before publishing and didn't check.
when first installing android studio and everything, install sdk to a new file like C:\Android\sdk and make sure all the next setup sdk items point to the folder you installed sdk to. It will work fine now... it must have something to do with permissions in the appdata folder is what my guess is
import math
import turtle
ws = turtle.Screen()
ws.bgcolor("lightblue")
fred = turtle.Turtle()
for angle in range(360):
y = math.sin(math.radians(angle))
fred.goto(angle, y * 80)
ws.exitonclick()
you can init placeholder in you select html code in two level such as:
<select class="form-control select2" style="width: 100%;" data-placeholder="Select a State">
<option></option>
<option>?????</option>
<option>????</option>
<option>??????</option>
<option>?????</option>
<option>?????</option>
<option>?????</option>
<option>???</option>
</select>
1.set data-placeholder attribute in your select tag 2.set empty tag in first of your select tag
You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations
Update
The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:
I have seen other code which I have inherited which uses SELECT TOP 100 PERCENT
The reason for this is simple: Enterprise Manager used to try to be helpful and format your code to include this for you. There was no point ever trying to remove it as it didn't really hurt anything and the next time you went to change it EM would insert it again.
We can also use logging to print data on the console.
Example:
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
You start looking near that code that you know ran, and you stop looking when you reach the code you know didn't run.
What you're looking for is probably some place where your program calls a function through a function pointer, but that pointer is null.
It's also possible you have stack corruption. You might have overwritten a function's return address with zero, and the exception occurs at the end of the function. Check for possible buffer overflows, and if you are calling any DLL functions, make sure you used the right calling convention and parameter count.
This isn't an ordinary case of using a null pointer, like an unassigned object reference or PChar. In those cases, you'll have a non-zero "at address x" value. Since the instruction occurred at address zero, you know the CPU's instruction pointer was not pointing at any valid instruction. That's why the debugger can't show you which line of code caused the problem — there is no line of code. You need to find it by finding the code that lead up to the place where the CPU jumped to the invalid address.
The call stack might still be intact, which should at least get you pretty close to your goal. If you have stack corruption, though, you might not be able to trust the call stack.
“Failed to configure a DataSource” error. First, we fixed the issue by defining the data source. Next, we discussed how to work around the issue without configuring the data source at all.
https://www.baeldung.com/spring-boot-failed-to-configure-data-source
I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).
Don't forget that integers can be negative:
^\s*-?[0-9]{1,10}\s*$
Here's the meaning of each part:
^
: Match must start at beginning of string\s
: Any whitespace character
*
: Occurring zero or more times-
: The hyphen-minus character, used to denote a negative integer
?
: May or may not occur[0-9]
: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
{1,10}
: Occurring at least one, but not more than ten times\s
: Any whitespace character
*
: Occurring zero or more times$
: Match must end at end of stringThis ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.
I was having a hard time finding a way to actually separate the dollar amount and the amount after the decimal. I think I figured it out mostly and thought to share if any of yall were having trouble
So basically...
if price is 1234.44... whole would be 1234 and decimal would be 44 or
if price is 1234.01... whole would be 1234 and decimal would be 01 or
if price is 1234.10... whole would be 1234 and decimal would be 10
and so forth
$price = 1234.44;
$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters
if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }
echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;
Also checkout the answer in this post: https://stackoverflow.com/a/9347871/1338557
It suggests use of library called ucsv.py. Short and simple replacement for CSV written to address the encoding problem(utf-8) for Python 2.7. Also provides support for csv.DictReader
Edit: Adding sample code that I used:
import ucsv as csv
#Read CSV file containing the right tags to produce
fileObj = open('awol_title_strings.csv', 'rb')
dictReader = csv.DictReader(fileObj, fieldnames = ['titles', 'tags'], delimiter = ',', quotechar = '"')
#Build a dictionary from the CSV file-> {<string>:<tags to produce>}
titleStringsDict = dict()
for row in dictReader:
titleStringsDict.update({unicode(row['titles']):unicode(row['tags'])})
I think the most simple way has not been included already (almost). Instead of using Behaviours which adds new dependencies just use attached properties:
using System;
using System.Windows;
using System.Windows.Controls;
public class DialogButtonManager
{
public static readonly DependencyProperty IsAcceptButtonProperty = DependencyProperty.RegisterAttached("IsAcceptButton", typeof(bool), typeof(DialogButtonManager), new FrameworkPropertyMetadata(OnIsAcceptButtonPropertyChanged));
public static readonly DependencyProperty IsCancelButtonProperty = DependencyProperty.RegisterAttached("IsCancelButton", typeof(bool), typeof(DialogButtonManager), new FrameworkPropertyMetadata(OnIsCancelButtonPropertyChanged));
public static void SetIsAcceptButton(UIElement element, bool value)
{
element.SetValue(IsAcceptButtonProperty, value);
}
public static bool GetIsAcceptButton(UIElement element)
{
return (bool)element.GetValue(IsAcceptButtonProperty);
}
public static void SetIsCancelButton(UIElement element, bool value)
{
element.SetValue(IsCancelButtonProperty, value);
}
public static bool GetIsCancelButton(UIElement element)
{
return (bool)element.GetValue(IsCancelButtonProperty);
}
private static void OnIsAcceptButtonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
Button button = sender as Button;
if (button != null)
{
if ((bool)e.NewValue)
{
SetAcceptButton(button);
}
else
{
ResetAcceptButton(button);
}
}
}
private static void OnIsCancelButtonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
Button button = sender as Button;
if (button != null)
{
if ((bool)e.NewValue)
{
SetCancelButton(button);
}
else
{
ResetCancelButton(button);
}
}
}
private static void SetAcceptButton(Button button)
{
Window window = Window.GetWindow(button);
button.Command = new RelayCommand(new Action<object>(ExecuteAccept));
button.CommandParameter = window;
}
private static void ResetAcceptButton(Button button)
{
button.Command = null;
button.CommandParameter = null;
}
private static void ExecuteAccept(object buttonWindow)
{
Window window = (Window)buttonWindow;
window.DialogResult = true;
}
private static void SetCancelButton(Button button)
{
Window window = Window.GetWindow(button);
button.Command = new RelayCommand(new Action<object>(ExecuteCancel));
button.CommandParameter = window;
}
private static void ResetCancelButton(Button button)
{
button.Command = null;
button.CommandParameter = null;
}
private static void ExecuteCancel(object buttonWindow)
{
Window window = (Window)buttonWindow;
window.DialogResult = false;
}
}
Then just set it on your dialog buttons:
<UniformGrid Grid.Row="2" Grid.Column="1" Rows="1" Columns="2" Margin="3" >
<Button Content="Accept" IsDefault="True" Padding="3" Margin="3,0,3,0" DialogButtonManager.IsAcceptButton="True" />
<Button Content="Cancel" IsCancel="True" Padding="3" Margin="3,0,3,0" DialogButtonManager.IsCancelButton="True" />
</UniformGrid>
Try list comprehension and string.strip()
:
>>> mystr = "L1\nL2\n\nL3\nL4\n \n\nL5"
>>> mystr.split('\n')
['L1', 'L2', '', 'L3', 'L4', ' ', '', 'L5']
>>> [line for line in mystr.split('\n') if line.strip() != '']
['L1', 'L2', 'L3', 'L4', 'L5']
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
The listed return type of the method is Task<string>
. You're trying to return a string
. They are not the same, nor is there an implicit conversion from string to Task<string>
, hence the error.
You're likely confusing this with an async
method in which the return value is automatically wrapped in a Task
by the compiler. Currently that method is not an async method. You almost certainly meant to do this:
private async Task<string> methodAsync()
{
await Task.Delay(10000);
return "Hello";
}
There are two key changes. First, the method is marked as async
, which means the return type is wrapped in a Task
, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await
model always avoid blocking waits when you can. Task.Delay
is a task that will be completed after the specified number of milliseconds. By await
-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).
If you prefer a 4.0 way of doing it, without using await
, you can do this:
private Task<string> methodAsync()
{
return Task.Delay(10000)
.ContinueWith(t => "Hello");
}
The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await
we aren't leveraging here.
If your Thread.Sleep(10000)
is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run
:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
SomeLongRunningMethod();
return "Hello";
});
}
Or more likely:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
return SomeLongRunningMethodThatReturnsAString();
});
}
This will
/\bword\b/.test("Thisword is not valid");
return false
, when this one
/\bword\b/.test("This word is valid");
will return true
.
JSON in any HTML tag except <script>
tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
If you want immediate first child you need
$(element).first();
If you want particular first element in the dom from your element then use below
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");
try out : http://jsfiddle.net/vgGbc/2/
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
Use
string += '=' * (-len(string) % 4) # restore stripped '='s
Credit goes to a comment somewhere here.
>>> import base64
>>> enc = base64.b64encode('1')
>>> enc
>>> 'MQ=='
>>> base64.b64decode(enc)
>>> '1'
>>> enc = enc.rstrip('=')
>>> enc
>>> 'MQ'
>>> base64.b64decode(enc)
...
TypeError: Incorrect padding
>>> base64.b64decode(enc + '=' * (-len(enc) % 4))
>>> '1'
>>>
Just as a note you can also use this for iPads:
activityViewController.popoverPresentationController?.sourceView = sender
So the popover pops from the sender (the button in that case).
There is a file in your git root directory named .gitignore
. It's a file, not a command. You just need to insert the names of the files that you want to ignore, and they will automatically be ignored. For example, if you wanted to ignore all emacs autosave files, which end in ~
, then you could add this line:
*~
If you want to remove the unwanted files from your branch, you can use git add -A
, which "removes files that are no longer in the working tree".
Note: What I called the "git root directory" is simply the directory in which you used git init
for the first time. It is also where you can find the .git
directory.
you have various ways to distinct values on one column or multi columns.
using the GROUP BY
SELECT DISTINCT MIN(o.tblFruit_ID) AS tblFruit_ID,
o.tblFruit_FruitType,
MAX(o.tblFruit_FruitName)
FROM tblFruit AS o
GROUP BY
tblFruit_FruitType
using the subquery
SELECT b.tblFruit_ID,
b.tblFruit_FruitType,
b.tblFruit_FruitName
FROM (
SELECT DISTINCT(tblFruit_FruitType),
MIN(tblFruit_ID) tblFruit_ID
FROM tblFruit
GROUP BY
tblFruit_FruitType
) AS a
INNER JOIN tblFruit b
ON a.tblFruit_ID = b.tblFruit_I
using the join with subquery
SELECT t1.tblFruit_ID,
t1.tblFruit_FruitType,
t1.tblFruit_FruitName
FROM tblFruit AS t1
INNER JOIN (
SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
tblFruit_FruitType
FROM tblFruit
GROUP BY
tblFruit_FruitType
) AS t2
ON t1.tblFruit_ID = t2.tblFruit_ID
using the window functions only one column distinct
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName
FROM (
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName,
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID)
rn
FROM tblFruit
) t
WHERE rn = 1
using the window functions multi column distinct
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName
FROM (
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName,
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType, tblFruit_FruitName
ORDER BY tblFruit_ID) rn
FROM tblFruit
) t
WHERE rn = 1
Change this line:
if (typeof(T) == typeof(string))
For this line:
if (t.GetType() == typeof(string))
If you forget to run:
php artisan key:generate
You would be face this error : Composer could not find a composer.json
sort()
. This will give a new array with numeric keys starting from 0
.asort()
.See also the comparison table of sorting functions in PHP.
As many folks already alluded to, this is a 32 vs. 64 bit problem for both Eclipse and Java. You cannot mix up 32 and 64 bit. Since Eclipse doesn't use JAVA_HOME
, you'll likely have to alter your PATH prior to launching Eclipse to ensure you are using not only the appropriate version of Java, but also if 32 or 64 bit (or modify the INI file as Jayath noted).
If you are installing Eclipse from a company-share, you should ensure you can tell which Eclipse version you are unzipping, and unzip to the appropriate Program Files directory to help keep track of which is which, then change the PATH (either permanently via (Windows) Control Panel -> System or set PATH=/path/to/32 or 64bit/java/bin;%PATH%
(maybe create a batch file if you don't want to set it in your system and/or user environment variables). Remember, 32-bit is in Program files (x86).
If unsure, just launch Eclipse, if you get the error, change your PATH to the other 'bit' version of Java, and then try again. Then move the Eclipse directory to the appropriate Program Files directory.
This works for me on Java 6
ServerSocket serverSocket = new ServerSocket(0);
System.out.println("listening on port " + serverSocket.getLocalPort());
Simply use
SELECT DATEPART(YEAR, SomeDateColumn)
It will return the portion of a DATETIME type that corresponds to the option you specify. SO DATEPART(YEAR, GETDATE()) would return the current year.
Can pass other time formatters instead of YEAR like
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.
Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).
In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:
log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/tomcat.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
Simplest would be to change the line:
log4j.rootLogger=DEBUG, R
To something like:
log4j.rootLogger=WARN, R
But if you still want your own DEBUG level output from your own classes add a line that says:
log4j.category.com.mypackage=DEBUG
Reading up a bit on Log4J and Commons-Logging will help you understand all this.
Here is one simple PHP Script which gets exchange rate between GBP and USD
<?php
$amount = urlencode("1");
$from_GBP0 = urlencode("GBP");
$to_usd= urlencode("USD");
$Dallor = "hl=en&q=$amount$from_GBP0%3D%3F$to_usd";
$US_Rate = file_get_contents("http://google.com/ig/calculator?".$Dallor);
$US_data = explode('"', $US_Rate);
$US_data = explode(' ', $US_data['3']);
$var_USD = $US_data['0'];
echo $to_usd;
echo $var_USD;
echo '<br/>';
?>
Google currency rates are not accurate google itself says ==> Google cannot guarantee the accuracy of the exchange rates used by the calculator. You should confirm current rates before making any transactions that could be affected by changes in the exchange rates. Foreign currency rates provided by Citibank N.A. are displayed under licence. Rates are for information purposes only and are subject to change without notice. Rates for actual transactions may vary and Citibank is not offering to enter into any transaction at any rate displayed.
Aside from the orders-of-magnitude performance advantage over heap allocation, stack allocation is preferable for long running server applications. Even the best managed heaps eventually get so fragmented that application performance degrades.
It provides human readable version of output rather "Object": Example:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def Norm(self):
return "%s is a %s" % (self.name, self.species)
if __name__=='__main__':
a = Pet("jax", "human")
print a
returns
<__main__.Pet object at 0x029E2F90>
while code with "str" return something different
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
if __name__=='__main__':
a = Pet("jax", "human")
print a
returns:
jax is a human
jQuery('#testID2').find('.test2').replaceWith('.test3');
Semantically, you are selecting the element with the ID testID2
, then you are looking for any descendent elements with the class test2
(does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3
) that also do not exist.
You need to do this:
jQuery('#testID2').addClass('test3').removeClass('test2');
This selects the element with the ID testID2
, then adds the class test3
to it. Last, it removes the class test2
from that element.
I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.
I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.
If you are at the office and behind the company proxy, try to imports all company proxy cacert into jre\lib\security
because gradle uses jre's certificates.
Plus, config your gradle.properties. It should work
More details go to that thread: https://groups.google.com/forum/#!msg/adt-dev/kdP2iNgcQFM/BDY7H0os18oJ
Query below should help you achieve what you want.
select scountry, headofstate from data
where data.scountry like 'a%'and ttlppl>=100000
I tried all the mentioned things above but could not resolve the issue. I am using SQLite and my SQLite file was in the resources directory.
a) Set Up done for IDE
I need to manually add below lines in the .classpath file of my project.
<classpathentry kind="src" path="resources"/>
<classpathentry kind="output" path="target/classes"/>
After that, I refreshed and Cleaned the project from MenuBar at the top. like Project->Clean->My Project Name.
After that, I run the project and problem resolved.
application.properties for my project is
spring.datasource.url=jdbc:sqlite:resources/apiusers.sqlite
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.jpa.properties.hibernate.dialect=com.enigmabridge.hibernate.dialect.SQLiteDialect
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
b) Set Up done if Jar deployment throw same error
You need to add following lines to your pom.xml
<build>
<resources>
<resource>
<directory>resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>
May be it may help someone.
This seems to work fine:
<button onclick="location.href='mailto:[email protected]';">send mail</button>
Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:
def greeting(name):
return 'Hello, {}'.format(name)
can now be written as this:
def greeting(name: str) -> str:
return 'Hello, {}'.format(name)
As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.
for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.
From here
If not Exists (select loginname from master.dbo.syslogins
where name = @loginName and dbname = 'PUBS')
Begin
Select @SqlStatement = 'CREATE LOGIN ' + QUOTENAME(@loginName) + '
FROM WINDOWS WITH DEFAULT_DATABASE=[PUBS], DEFAULT_LANGUAGE=[us_english]')
EXEC sp_executesql @SqlStatement
End
It's an exclusive or (XOR). If I remember correctly, when doing bitwise mathematics the dot (.) means AND and the plus (+) means OR. Putting a circle around the plus to mean XOR is consistent with the style used for OR.
Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.
Hope this helps.
In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:
_.remove(obj.subTopics, (currentObject) => {
return currentObject.subTopicId === stToDelete;
});
OR
obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
return currentObject.subTopicId !== stToDelete;
});
There are lots of free tools that can do this.
I use PDFTK (a open source cross-platform command-line tool) for things like that.
Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.
You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).
To make a POST request, you need to create a <form>
. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.
As of [email protected], we can just easily use the NavLink with activeClassName instead of Link. Example:
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
class NavBar extends Component {
render() {
return (
<div className="navbar">
<ul>
<li><NavLink to='/1' activeClassName="active">1</NavLink></li>
<li><NavLink to='/2' activeClassName="active">2</NavLink></li>
<li><NavLink to='/3' activeClassName="active">3</NavLink></li>
</ul>
</div>
);
}
}
Then in your CSS file:
.navbar li>.active {
font-weight: bold;
}
The NavLink will add your custom styling attributes to the rendered element based on the current URL.
Document is here
First a link to some documentation of fork()
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.
So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.
If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().
pid_t pid = fork()
if(pid == 0) {
printf("this is a child: my new unique pid is %d\n", getpid());
} else {
printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}
and below is some inline comments on your code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1 == 0){
/* This is child A */
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
/* This is parent A */
/* Child B and C will never reach this code */
pid3=fork(); /* D */
if(pid3==0) {
/* This is child D fork'ed from parent A */
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0)) {
/* pid1 will never be 0 here so this is dead code */
printf("Level 1\n");
}
if(pid1 !=0) {
/* This is always true for both parent and child E */
printf("Level 2\n");
}
if(pid2 !=0) {
/* This is parent E (same as parent A) */
printf("Level 3\n");
}
if(pid3 !=0) {
/* This is parent D (same as parent A) */
printf("Level 4\n");
}
}
return 0;
}
df[df.duplicated(['ID'], keep=False)]
it'll return all duplicated rows back to you.
According to documentation:
keep : {‘first’, ‘last’, False}, default ‘first’
- first : Mark duplicates as True except for the first occurrence.
- last : Mark duplicates as True except for the last occurrence.
- False : Mark all duplicates as True.
Depending on what you want to accomplish within the loop, iterate over one of these instead:
countries.keySet()
countries.entrySet()
countries.values()
To convert from integers < 256 to binary, use the chr
function. So you're looking at doing the following.
newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))
SIMPLE..
First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)
The right answer is
Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.
I'm still getting my feet wet with Node.js, but I have a few ideas. first, I believe you need to use execFile
instead of spawn
; execFile
is for when you have the path to a script, whereas spawn
is for executing a well-known command that Node.js can resolve against your system path.
var child = require('child_process').execFile('path/to/script', [
'arg1', 'arg2', 'arg3',
], function(err, stdout, stderr) {
// Node.js will invoke this callback when process terminates.
console.log(stdout);
});
var child = require('child_process').execFile('path/to/script', [
'arg1', 'arg2', 'arg3' ]);
// use event hooks to provide a callback to execute when data are available:
child.stdout.on('data', function(data) {
console.log(data.toString());
});
Further, there appear to be options whereby you can detach the spawned process from Node's controlling terminal, which would allow it to run asynchronously. I haven't tested this yet, but there are examples in the API docs that go something like this:
child = require('child_process').execFile('path/to/script', [
'arg1', 'arg2', 'arg3',
], {
// detachment and ignored stdin are the key here:
detached: true,
stdio: [ 'ignore', 1, 2 ]
});
// and unref() somehow disentangles the child's event loop from the parent's:
child.unref();
child.stdout.on('data', function(data) {
console.log(data.toString());
});
I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round
function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...
The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places)
is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:
>>> round(52.15, 1)
52.1
With a naive understanding of what round
does, this looks wrong: surely it should be rounding up to 52.2
rather than down to 52.1
? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.
So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n
-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):
First the numeric literal 52.15
gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47
, or 52.14999999999999857891452847979962825775146484375
.
Internally as the first step of the round
operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15
, we end up rounding down and getting a string 52.1
. This explains why we're getting 52.1
as the final output instead of 52.2
.
Then in the second step of the round
operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1
, which is now 7332423143312589 * 2**-47
, or 52.10000000000000142108547152020037174224853515625
.
Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1
as the final output.
In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr
implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:
>>> x = 15.34509809234
>>> x
15.34509809234
Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:
>>> round(52.15, 1)
52.200000000000003
Not only do we round in the opposite direction, getting 52.2
instead of 52.1
, but the displayed value doesn't even print as 52.2
! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round
that's broken, it's user expectations. (Okay, okay, round
is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)
Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.
So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.
If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:
>>> format(66.66666666666, '.4f')
'66.6667'
>>> format(1.29578293, '.6f')
'1.295783'
Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.
>>> format(52.15, '.1f')
'52.1'
If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal
type. Doing a decimal round on the Decimal
type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal
module gives you better control of the rounding mode. In Python 3, round
does the job directly. In Python 2, you need the quantize
method.
>>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
Decimal('66.6667')
>>> Decimal('1.29578293').quantize(Decimal('1e-6'))
Decimal('1.295783')
In rare cases, the two-argument version of round
really is what you want: perhaps you're binning floats into bins of size 0.01
, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round
builtin based on those cases alone.
Some blogs/websites to check out:
Currently, Josh Smith has a "From Russia With Love" article that can be of some use to you.
var cubes = [["string", "string"], ["string", "string"]];
for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
I would do it this this way:
Stage all unstaged changes.
git add .
Stash the changes.
git stash save
Sync with remote.
git pull -r
Reapply the local changes.
git stash pop
or
git stash apply
This error generally occurs because we have some values in the referencing field of the child table, which do not exist in the referenced/candidate field of the parent table.
Sometimes, we may get this error when we are applying Foreign Key constraints to existing table(s), having data in them already. Some of the other answers are suggesting to delete the data completely from child table, and then apply the constraint. However, this is not an option when we already have working/production data in the child table. In most scenarios, we will need to update the data in the child table (instead of deleting them).
Now, we can utilize Left Join
to find all those rows in the child table, which does not have matching values in the parent table. Following query would be helpful to fetch those non-matching rows:
SELECT child_table.*
FROM child_table
LEFT JOIN parent_table
ON parent_table.referenced_column = child_table.referencing_column
WHERE parent_table.referenced_column IS NULL
Now, you can generally do one (or more) of the following steps to fix the data.
null
as well.Once the data is fixed, we can apply the Foreign key constraint using ALTER TABLE
syntax.
For Bootstrap 4
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" placeholder="Start"/>_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text" id="">-</span>_x000D_
</div>_x000D_
<input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
the proper way is:
.attr({target:'nw', title:'Opens in a new window'})
That looks fine, unless you want to pass it as Model string
public class HomeController : Controller
{
public ActionResult Index()
{
string model = "<HTML></HTML>";
return View(model);
}
}
@model string
@{
ViewBag.Title = "Index";
}
@Html.Raw(Model)
Since some of the answers give here relate to setting up SMTP in general (and not just for @shinod particular issue where it had been working and stopped), I thought it would be helpful if I updated the answer because this is a lot simpler to do now than it used to be :-)
In PHP 4 the PEAR Mail package is typically already installed, and this really simple tutorial shows you the few lines of code that you need to add to your php file http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm
Most hosting companies list the SMTP settings that you'll need. I use JustHost, and they list theirs at https://my.justhost.com/cgi/help/26 (under Outgoing Mail Server)
Put a colorscheme
directive in your .vimrc
file, for example:
colorscheme morning
InOrder
helps you to do that.
ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);
Mockito.doNothing().when(firstMock).methodOne();
Mockito.doNothing().when(secondMock).methodTwo();
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);
//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();
I ran into this issue when pulling down a TFS project to my local machine. Allegedly, it was working fine on the guy's machine who wrote it. I simply changed this...
WshShellClass shellClass = new WshShellClass();
To this...
WshShell shellClass = new WshShell();
Now, it is working like a champ!
I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:
'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'
Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.
// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));
I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.
Depending on the browsers you are targeting, you can use the JSON.stringify
function to produce JSON strings.
See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.
In your case:
var array = [];
$("input[class=email]").each(function() {
array.push({
title: $(this).attr("title"),
email: $(this).val()
});
});
// then to get the JSON string
var jsonString = JSON.stringify(array);
npm version
is probably the correct answer. Just to give an alternative I recommend grunt-bump. It is maintained by one of the guys from angular.js.
Usage:
grunt bump
>> Version bumped to 0.0.2
grunt bump:patch
>> Version bumped to 0.0.3
grunt bump:minor
>> Version bumped to 0.1.0
grunt bump
>> Version bumped to 0.1.1
grunt bump:major
>> Version bumped to 1.0.0
If you're using grunt anyway it might be the simplest solution.
I had significant headaches with these methods before, I recommend you avoid any variant of UrlEncode
, and instead use Uri.EscapeDataString
- at least that one has a comprehensible behavior.
Let's see...
HttpUtility.UrlEncode(" ") == "+" //breaks ASP.NET when used in paths, non-
//standard, undocumented.
Uri.EscapeUriString("a?b=e") == "a?b=e" // makes sense, but rarely what you
// want, since you still need to
// escape special characters yourself
But my personal favorite has got to be HttpUtility.UrlPathEncode - this thing is really incomprehensible. It encodes:
It also has the lovelily specific MSDN documentation "Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client." - without actually explaining what it does. You are less likely to shoot yourself in the foot with an Uzi...
In short, stick to Uri.EscapeDataString.
In my case the only way I could keep using GetGroups() without any expcetion was adding the user (USER_WITH_PERMISSION) to the group which has permission to read the AD (Active Directory). It's extremely essential to construct the PrincipalContext passing this user and password.
var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();
Steps you may follow inside Active Directory to get it working:
- Into Active Directory create a group (or take one) and under secutiry tab add "Windows Authorization Access Group"
- Click on "Advanced" button
- Select "Windows Authorization Access Group" and click on "View"
- Check "Read tokenGroupsGlobalAndUniversal"
- Locate the desired user and add to the group you created (taken) from the first step
Depends on the version, 4 is by value, 5 is by reference.
You can use Environment.Exit(0);
and Application.Exit
Environment.Exit(0)
is cleaner.
There isn't really a formal manual, because there's no single style or standard.
So long as you understand the rules of identifier naming you can use whatever you like.
In practice, I find it easier to use lower_case_underscore_separated_identifiers
because it isn't necessary to "Double Quote"
them everywhere to preserve case, spaces, etc.
If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42"
you'd be free to do that, though it'd be pain to type everywhere.
The main things to understand are:
Unless double-quoted, identifiers are case-folded to lower-case, so MyTable
, MYTABLE
and mytable
are all the same thing, but "MYTABLE"
and "MyTable"
are different;
Unless double-quoted:
SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).
You must double-quote keywords if you wish to use them as identifiers.
In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with"
doesn't mean you should.
I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1
let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)
In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by
let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)
And in VC2, when close the view controller, as usual we can use:
self.dismiss(animated: true, completion: nil)
use binary search
public class FindSqrt {
public static void main(String[] strings) {
int num = 10000;
System.out.println(sqrt(num, 0, num));
}
private static int sqrt(int num, int min, int max) {
int middle = (min + max) / 2;
int x = middle * middle;
if (x == num) {
return middle;
} else if (x < num) {
return sqrt(num, middle, max);
} else {
return sqrt(num, min, middle);
}
}
}
The accepted answer changes shape for 2d arrays.
I present a solution here, using the Pandas dropna() functionality.
It works for 1D and 2D arrays. In the 2D case you can choose weather to drop the row or column containing np.nan
.
import pandas as pd
import numpy as np
def dropna(arr, *args, **kwarg):
assert isinstance(arr, np.ndarray)
dropped=pd.DataFrame(arr).dropna(*args, **kwarg).values
if arr.ndim==1:
dropped=dropped.flatten()
return dropped
x = np.array([1400, 1500, 1600, np.nan, np.nan, np.nan ,1700])
y = np.array([[1400, 1500, 1600], [np.nan, 0, np.nan] ,[1700,1800,np.nan]] )
print('='*20+' 1D Case: ' +'='*20+'\nInput:\n',x,sep='')
print('\ndropna:\n',dropna(x),sep='')
print('\n\n'+'='*20+' 2D Case: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna (rows):\n',dropna(y),sep='')
print('\ndropna (columns):\n',dropna(y,axis=1),sep='')
print('\n\n'+'='*20+' x[np.logical_not(np.isnan(x))] for 2D: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna:\n',x[np.logical_not(np.isnan(x))],sep='')
Result:
==================== 1D Case: ====================
Input:
[1400. 1500. 1600. nan nan nan 1700.]
dropna:
[1400. 1500. 1600. 1700.]
==================== 2D Case: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna (rows):
[[1400. 1500. 1600.]]
dropna (columns):
[[1500.]
[ 0.]
[1800.]]
==================== x[np.logical_not(np.isnan(x))] for 2D: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna:
[1400. 1500. 1600. 1700.]
ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
Use jsbeautifier instead of trying to do it manually.
Verify that your installation of PHP has been compiled with mysql support. Create a test web page containing <?php phpinfo(); exit(); ?>
and load it in your browser. Search the page for MySQL. If you don't see it, you need to recompile PHP with MySQL support, or reinstall a PHP package that has it built-in
You should look at RAND_MAX
for your particular compiler/environment.
I think you would see these results if rand()
is producing a random 16-bit number. (you seem to be assuming it will be a 32-bit number).
I can't promise this is the answer, but please post your value of RAND_MAX
, and a little more detail on your environment.
According to Documentation
git diff Shows changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes resulting from a merge, changes between two blob objects, or changes between two files on disk.
In git diff
- There's a significant difference between two dots ..
and 3 dots ...
in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.
Example: Let's assume we're checking out new branch from master and pushing some code in.
G---H---I feature (Branch)
/
A---B---C---D master (Branch)
Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature
or just git diff origin/master
,output: ( H, I
against A, B, C, D
)
Three dots - If we want to show the diffs between the last common ancestor (A
), aka the check point we started our new branch ,we use git diff origin/master...feature
,output: (H, I
against A
).
I'd rather use the 3 dots in most circumstances.
An alternative solution to the Turtle and Rabbit, not quite as nice, as I temporarily change the list:
The idea is to walk the list, and reverse it as you go. Then, when you first reach a node that has already been visited, its next pointer will point "backwards", causing the iteration to proceed towards first
again, where it terminates.
Node prev = null;
Node cur = first;
while (cur != null) {
Node next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
boolean hasCycle = prev == first && first != null && first.next != null;
// reconstruct the list
cur = prev;
prev = null;
while (cur != null) {
Node next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return hasCycle;
Test code:
static void assertSameOrder(Node[] nodes) {
for (int i = 0; i < nodes.length - 1; i++) {
assert nodes[i].next == nodes[i + 1];
}
}
public static void main(String[] args) {
Node[] nodes = new Node[100];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = new Node();
}
for (int i = 0; i < nodes.length - 1; i++) {
nodes[i].next = nodes[i + 1];
}
Node first = nodes[0];
Node max = nodes[nodes.length - 1];
max.next = null;
assert !hasCycle(first);
assertSameOrder(nodes);
max.next = first;
assert hasCycle(first);
assertSameOrder(nodes);
max.next = max;
assert hasCycle(first);
assertSameOrder(nodes);
max.next = nodes[50];
assert hasCycle(first);
assertSameOrder(nodes);
}
You'll need some kind of abstract factory of one sort or another to pass the buck to:
interface Factory<E> {
E create();
}
class SomeContainer<E> {
private final Factory<E> factory;
SomeContainer(Factory<E> factory) {
this.factory = factory;
}
E createContents() {
return factory.create();
}
}
Quoting the docs.
The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.
To get rid of the hash, we can use the router's history mode, which leverages the history.pushState API to achieve URL navigation without a page reload:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
When using history mode, the URL will look "normal," e.g. http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!
Within an htaccess file, the scope of the <Files>
directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).
So you can have:
<Files "log.txt">
Order Allow,Deny
Deny from all
</Files>
For Apache 2.4+, you'd use:
<Files "log.txt">
Require all denied
</Files>
In an htaccess file in your inscription
directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:
RewriteRule /?\.htaccess$ - [F,L]
RewriteRule ^/?inscription/log\.txt$ - [F,L]
You have
COPY files/* /test/
which expands toCOPY files/dir files/file1 files/file2 files/file /test/
.
If you split this up into individualCOPY
commands (e.g.COPY files/dir /test/
) you'll see that (for better or worse)COPY
will copy the contents of each argdir
into the destination directory. Not the argdir
itself, but the contents.I'm not thrilled with that fact that COPY doesn't preserve the top-level dir but its been that way for a while now.
so in the name of preserving a backward compatibility, it is not possible to COPY
/ADD
a directory structure.
The only workaround would be a series of RUN mkdir -p /x/y/z
to build the target directory structure, followed by a series of docker ADD
(one for each folder to fill).
(ADD
, not COPY
, as per comments)
You can make auto increment in SQL Modeler. In column properties window Click : General then Tick the box of Auto Increment. After that the auto increment window will be enabled for you.
On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.
Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:
C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl
. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False
That should allow your app to start correctly.
You can do like this :
List<String> temp = new ArrayList<String>(Arrays.asList("1", "12"));
I'm surprised how many answers here are just wrong. Echoing nothing into a file will fill the file with something like ECHO is ON
, and trying to echo $nul
into a file will literally place $nul
into the file. Additionally for PowerShell, echoing $null
into a file won't actually make a 0kb file, but something encoded as UCS-2 LE BOM
, which can get messy if you need to make sure your files don't have a byte-order mark.
After testing all the answers here and referencing some similar ones, I can guarantee these will work per console shell. Just change FileName.FileExtension
to the full or relative-path of the file you want to touch
; thanks to Keith Russell for the COPY NUL FILE.EXT
update:
copy NUL FileName.FileExtension
This will create a new file named whatever you placed instead of FileName.FileExtension
with a size of 0 bytes. If the file already exists it will basically copy itself in-place to update the timestamp. I'd say this is more of a workaround than 1:1 functionality with touch
but I don't know of any built-in tools for CMD that can accomplish updating a file's timestamp without changing any of its other content.
if not exist FileName.FileExtension copy NUL FileName.FileExtension
if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file} else {(ls FileName.FileExtension ).LastWriteTime = Get-Date}
Yes, it will work in-console as a one-liner; no requirement to place it in a PowerShell script file.
if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file}
A alternative using UTC timestamps. Also as others noted the day indicating 1st a month is 1 rather than 0. The month starts at 0 however.
var now = Date.now();
var year = new Date().getUTCFullYear();
var year_start = Date.UTC(year, 0, 1);
var day_length_in_ms = 1000*60*60*24;
var day_number = Math.floor((now - year_start)/day_length_in_ms)
console.log("Day of year " + day_number);
Here is a safe and reusable function for adding script to head section if its not already exist there.
see working example here: Example
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<style>
</style>
</head>
<body>
<input type="button" id="" style='width:250px;height:50px;font-size:1.5em;' value="Add Script" onClick="addScript('myscript')"/>
<script>
function addScript(filename)
{
// house-keeping: if script is allready exist do nothing
if(document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
{
alert("script is allready exist in head tag!")
}
else
{
// add the script
loadScript('/',filename + ".js");
}
}
function loadScript(baseurl,filename)
{
var node = document.createElement('script');
node.src = baseurl + filename;
document.getElementsByTagName('head')[0].appendChild(node);
alert("script added");
}
</script>
</body>
</html>
sSource = StringUtils.replace(sSource, "\\/", "/")
I suppose your html page is hosted on a different port. Same origin policy requires in most browsers that the loaded file be on the same port than the loading file.
Another one answer
static class ImmutableArray<T> {
private final T[] array;
private ImmutableArray(T[] a){
array = Arrays.copyOf(a, a.length);
}
public static <T> ImmutableArray<T> from(T[] a){
return new ImmutableArray<T>(a);
}
public T get(int index){
return array[index];
}
}
{
final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}
You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.
curl -X HEAD -i http://www.google.com
More here: https://serverfault.com/questions/140149/difference-between-curl-i-and-curl-x-head
The correct one for me is the Zuan solution. Be aware to add isset to $args->add_li_class
, however you got Notice: Undefined property: stdClass::$add_li_class
if you haven't set the property in all yours wp_nav_menu()
functions.
This is the function that worked for me:
function add_additional_class_on_li($classes, $item, $args) {
if(isset($args->add_li_class)) {
$classes[] = $args->add_li_class;
}
return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);
Good. I suggest creating a Value Object (Vo) that contains the fields you need. The code is simpler, we do not change the functioning of Jackson and it is even easier to understand. Regards!
With Windows 8.1 I couldn't find any .exd files using windows search. On the other hand, a cmd command dir *.exd /S
found the one file on my system.
In addition to the methods presented above, you need to make sure you use either std::Vector.reserve(), std::Vector.resize(), or construct the vector to size, to make sure your vector has enough elements in it to hold your data. if not, you will corrupt memory. This is true of either std::copy() or memcpy().
This is the reason to use vector.push_back(), you can't write past the end of the vector.
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date
if you want to compare dates, ignoring the time part, make an use of DateTime.Year
and DateTime.DayOfYear
properties.
code snippet
DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
Console.WriteLine("d1 < d2");
else
if (d1.DayOfYear < d2.DayOfYear)
Console.WriteLine("d1 < d2");
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
I saw the same error when the scope of the jackson-databind
dependency had been set to test
:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
<scope>test</scope>
</dependency>
Removing the <scope>
line fixed the issue.
Restarting SQL server will disconnect users. Easiest way I've found - good also if you want to take the server offline.
But for some very wierd reason the 'Take Offline' option doesn't do this reliably and can hang or confuse the management console. Restarting then taking offline works
Sometimes this is an option - if for instance you've stopped a webserver that is the source of the connections.
The getMyName
function in the snippet below returns the name of the calling function. It's a hack and relies on non-standard feature: Error.prototype.stack
. Note that format of the string returned by Error.prototype.stack
is implemented differently in different engines, so this probably won't work everywhere:
function getMyName() {_x000D_
var e = new Error('dummy');_x000D_
var stack = e.stack_x000D_
.split('\n')[2]_x000D_
// " at functionName ( ..." => "functionName"_x000D_
.replace(/^\s+at\s+(.+?)\s.+/g, '$1' );_x000D_
return stack_x000D_
}_x000D_
_x000D_
function foo(){_x000D_
return getMyName()_x000D_
}_x000D_
_x000D_
function bar() {_x000D_
return foo()_x000D_
}_x000D_
_x000D_
console.log(bar())
_x000D_
About other solutions: arguments.callee
is not allowed in strict mode and Function.prototype.caller
is non-standard and not allowed in strict mode.
executemany accept array of tuples
https://www.postgresqltutorial.com/postgresql-python/insert/
""" array of tuples """
vendor_list = [(value1,)]
""" insert multiple vendors into the vendors table """
sql = "INSERT INTO vendors(vendor_name) VALUES(%s)"
conn = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.executemany(sql,vendor_list)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
The answers above will work for changing the values.
If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:
go to your 'Formulas' tab
choose "Name Manager"
a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.
From the MySql site.
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
There is a very simple and easy solution to your question:
var districtId = 210;
if (DistrictsEnum[districtId] != null) {
// Returns 'undefined' if the districtId not exists in the DistrictsEnum
model.handlingDistrictId = districtId;
}
It's very simple just use a function on javaScript and call it onclick
<script type="text/javascript">
function change()
{
document.getElementById("catestory").style.backgroundColor="#666666";
}
</script>
<a href="#" onclick="change()">Change Bacckground Color</a>
In my case, when I changed the wshttpbinding
protocol from https
to http
it started working.
If you use Less you can directly use the following mixin:
.@{fa-css-prefix}-rotate-90 { .fa-icon-rotate(90deg, 1); }
I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.
An extended answer for remote IP db connections:
Step 1: Link servers
EXEC sp_addlinkedserver @server='SRV_NAME',
@srvproduct=N'',
@provider=N'SQLNCLI',
@datasrc=N'aaa.bbb.ccc.ddd';
EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'
...where SRV_NAME
is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd
is the ip address of the remote server hosting your SQLserver DB.
Step 2: Run your queries For instance:
SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table
...and that's it!
Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin
It is located in server administration rather than in SQL development.
For me, this helped: 1. Configuration properties/General/Platform Toolset = Windows XP (V110_xp) 2. C/C++ Preprocessor definitions, add "WIN32" 3. Linker/System/Minimum required version = 5.01
You will find the tomcat-users.xml in \Users\<Name>\AppData\Roaming\Netbeans\
. It exists at least twice on your machine, depending on the number of Tomcat installations you have.
DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
i fixed My issue by adding the annotation of @Lob which will create the byte[] in oracle as blob , but this annotation will create the field as oid which not work properly , To make byte[] created as bytea i made customer Dialect for postgres as below
Public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {
public PostgreSQLDialectCustom() {
System.out.println("Init PostgreSQLDialectCustom");
registerColumnType( Types.BLOB, "bytea" );
}
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
return BinaryTypeDescriptor.INSTANCE;
}
return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
}
}
Also need to override parameter for the Dialect
spring.jpa.properties.hibernate.dialect=com.ntg.common.DBCompatibilityHelper.PostgreSQLDialectCustom
more hint can be found her : https://dzone.com/articles/postgres-and-oracle
how to completely clear localstorage
localStorage.clear();
how to completely clear sessionstorage
sessionStorage.clear();
[...] Cookies ?
var cookies = document.cookie;
for (var i = 0; i < cookies.split(";").length; ++i)
{
var myCookie = cookies[i];
var pos = myCookie.indexOf("=");
var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
is there any way to get the value back after clear these ?
No, there isn't. But you shouldn't rely on this if this is related to a security question.
For Excel 2013:
http://blogmines.com/blog/how-to-import-text-file-in-excel-2013/
The key must be indexed to apply foreign key constraint. To do that follow the steps.
You will be able to assign DOCTOR_ID as foreign now.
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
I was facing the same problem. For my solution, I added br
enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:
+"<br>"+
Try this in your browser and see, it certainly works in my Internet Explorer.
For Android development, I use:
int color = Color.parseColor("#123456");
I personally don't see the need for a library for this. Looking at http://caniuse.com/#feat=clipboard it's pretty widely supported now, however you can still do things like checking to see if the functionality exists in the current client and simply hide the copy button if it doesn't.
import React from 'react';
class CopyExample extends React.Component {
constructor(props) {
super(props);
this.state = { copySuccess: '' }
}
copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
// This is just personal preference.
// I prefer to not show the whole text area selected.
e.target.focus();
this.setState({ copySuccess: 'Copied!' });
};
render() {
return (
<div>
{
/* Logical shortcut for only displaying the
button if the copy command exists */
document.queryCommandSupported('copy') &&
<div>
<button onClick={this.copyToClipboard}>Copy</button>
{this.state.copySuccess}
</div>
}
<form>
<textarea
ref={(textarea) => this.textArea = textarea}
value='Some text to copy'
/>
</form>
</div>
);
}
}
export default CopyExample;
Update: Rewritten using React Hooks in React 16.7.0-alpha.0
import React, { useRef, useState } from 'react';
export default function CopyExample() {
const [copySuccess, setCopySuccess] = useState('');
const textAreaRef = useRef(null);
function copyToClipboard(e) {
textAreaRef.current.select();
document.execCommand('copy');
// This is just personal preference.
// I prefer to not show the whole text area selected.
e.target.focus();
setCopySuccess('Copied!');
};
return (
<div>
{
/* Logical shortcut for only displaying the
button if the copy command exists */
document.queryCommandSupported('copy') &&
<div>
<button onClick={copyToClipboard}>Copy</button>
{copySuccess}
</div>
}
<form>
<textarea
ref={textAreaRef}
value='Some text to copy'
/>
</form>
</div>
);
}
From menu select: File->Invalidate Catches/Restart...
than in opened dialog select: "Invalidate and Restart" and wait to restart android studio.
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
Yes, the short-circuit evaluation for boolean expressions is the default behaviour in all the C-like family.
An interesting fact is that Java also uses the &
and |
as logic operands (they are overloaded, with int
types they are the expected bitwise operations) to evaluate all the terms in the expression, which is also useful when you need the side-effects.
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
You can use MultiIndex.droplevel
:
>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
>>> df = pd.DataFrame([[1,2], [3,4]], columns=cols)
>>> df
a
b c
0 1 2
1 3 4
[2 rows x 2 columns]
>>> df.columns = df.columns.droplevel()
>>> df
b c
0 1 2
1 3 4
[2 rows x 2 columns]
Using a Windows symbolic link from the C:\Users{username}\AppData\Roaming\npm and C:\Users{username}\AppData\Roaming\npm-cache paths to the destination worked great for me.
As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:
Click "Run as different user"
Enter credentials of the other user in the next pop-up window
Now when you debug the solution it will be with the other user's permissions.
Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
Typically you would always put the hyphen first in the []
match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]
Please refer to this link. You can have any button you want just use javascript to submit the form
To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan
to that activity in android manifest file. for example
<activity
android:name="com.comapny.applicationname.activityname"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible|adjustPan"/>
For persistent key/value storage, you can use kv-bash
, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash
Usage
git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash
Try create some permanent variables
kvset myName xyz
kvset myEmail [email protected]
#read the varible
kvget myEmail
#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)
Under Linux, What worked for me was John Anderson's (sontek) guide, which you can find at this link. However, I cheated and just used his easy configuration setup from his Git repostiory:
git clone -b vim https://github.com/sontek/dotfiles.git
cd dotfiles
./install.sh vim
His configuration is fairly up to date as of today.
vim
also can convert files from UNIX to DOS format. For example:
vim hello.txt <<EOF
:set fileformat=dos
:wq
EOF
A little late to the party, but...
The other answers do a good job of explaining what effect the [ChildActionOnly]
attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render @Html.Partial("_MyParialView")
directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.
This can come in handy, for example, in _Layout.cshtml
. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout
can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render @Html.Action
in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout
page need not have a model. It follows that all other view models need not inherit from any base view model.
I'm sure there are other reasons to use the [ChildActionOnly]
attribute, but this seems like a good one to me, so I thought I'd share.
If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.
You can follow the image i shared to unstash if u accidentally tapped stashing.
Assuming your "date" column is not actually a date.
Select convert(varchar(8),cast('12/24/2016' as date),112)
or
Select format(cast('12/24/2016' as date),'yyyyMMdd')
Returns
20161224
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
for the above problem ur password in the system should matches with the password u have passed in the program because when u run the program it checks system's password as u have given root as a user so gives u an error and at the same time the record is not deleted from the database.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
class Delete
{
public static void main(String []k)
{
String url="jdbc:mysql://localhost:3306/student";
String user="root";
String pass="jacob234";
try
{
Connection myConnection=DriverManager.getConnection(url,user,pass);
Statement myStatement=myConnection.createStatement();
String deleteQuery="delete from students where id=2";
myStatement.executeUpdate(deleteQuery);
System.out.println("delete completed");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Keep ur system password as jacob234 and then run the code.
SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use
It is certified for SharePoint 2007
The list of supported operations for Lists.asmx could be found here
In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:
<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Announcements",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
$("#tasksUL").append(liHtml);
});
}
});
});
</script>
<ul id="tasksUL"/>
You can code atoi()
for fun:
int my_getnbr(char *str)
{
int result;
int puiss;
result = 0;
puiss = 1;
while (('-' == (*str)) || ((*str) == '+'))
{
if (*str == '-')
puiss = puiss * -1;
str++;
}
while ((*str >= '0') && (*str <= '9'))
{
result = (result * 10) + ((*str) - '0');
str++;
}
return (result * puiss);
}
You can also make it recursive, which can fold in 3 lines.
completed = (id) => {
var details = {
'id': id,
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch(markcompleted, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson, 'res JSON');
if (responseJson.status == "success") {
console.log(this.state);
alert("your todolist is completed!!");
}
})
.catch((error) => {
console.error(error);
});
};
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.black));
yourTextView.setTypeface(face);
Using boto3
import logging
import boto3
from botocore.exceptions import ClientError
def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
# If S3 object_name was not specified, use file_name
if object_name is None:
object_name = file_name
# Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
logging.error(e)
return False
return True
For more:- https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html
TL;DR: dependency conflicts: Updating one requires (by it's requirements) to downgrade another
You are right:
conda update --all
is actually the way to go1. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x).
But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.
e.g. X requires Y <5.0, so Y will never be >= 5.0
That's why you 'cannot' upgrade them all.
To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.
A safe way you can try is to add conda-forge as a channel when upgrading (add -c conda-forge
as a flag) or any other channel you find that contains your package if you really need this new version. This way conda does also search in this places for available packages.
Considering your update: You can upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:
X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0
So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.
(this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies)
So you still cannot upgrade them all by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an ignore-dependencies and force-command. But that is only to hack your way around issues, definitely not the normal-user case!
1 If you actually want to update the packages of your installation, which you usually don't. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (conda create -n myenv
and then conda activate myenv
). Executing conda update --all
inside such an environment will update the packages inside this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.
It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".
.img {
width: 100vw;
height: 100vh;
}
I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null
means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture
, it will be okay.
If anyone's interested in reproducing this:
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy",
new CultureInfo("de-DE"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("en-US"));
// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
CultureInfo.InvariantCulture);
// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy",
new CultureInfo("de-DE"));
@VonC already gave a very nice answer, but for completeness here is a little script I have been using---and which also nukes any errand Docker processes should you have some:
#!/bin/bash
imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
echo docker rmi ${imgs}
docker rmi ${imgs}
else
echo "No images to remove"
fi
procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
echo docker rm ${procs}
docker rm ${procs}
else
echo "No processes to purge"
fi
This function extracts images from video with 1 fps, IN ADDITION it identifies the last frame and stops reading also:
import cv2
import numpy as np
def extract_image_one_fps(video_source_path):
vidcap = cv2.VideoCapture(video_source_path)
count = 0
success = True
while success:
vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))
success,image = vidcap.read()
## Stop when last frame is identified
image_last = cv2.imread("frame{}.png".format(count-1))
if np.array_equal(image,image_last):
break
cv2.imwrite("frame%d.png" % count, image) # save frame as PNG file
print '{}.sec reading a new frame: {} '.format(count,success)
count += 1
This is a onliner for copying a single file while running a tomcat container.
docker run -v /PATH_TO_WAR/sample.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
If the column is of type char
then you need to append the value you are querying with spaces, please refer to this question here . This in addition to using COLLATE NOCASE
or one of the other solutions (upper(), etc).
This works even if the script is sourced:
source "$( dirname "${BASH_SOURCE[0]}" )/incl.sh"
Try adding the property line-height: 22px;
to the code.