Here is the answer:
$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
Swift 2 version
extension NSTimeInterval {
func toMM_SS() -> String {
let interval = self
let componentFormatter = NSDateComponentsFormatter()
componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .Pad
componentFormatter.allowedUnits = [.Minute, .Second]
return componentFormatter.stringFromTimeInterval(interval) ?? ""
}
}
let duration = 326.4.toMM_SS()
print(duration) //"5:26"
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Edit:
hours, minutes, seconds
above will be the hours, minutes and seconds after converting yourdate
to System Timezone!
A rather roundabout way, just for completeness:
for /f "delims=" %i in ('type CON') do set inp=%i
Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.
See THIS previous SO post on using a variable on the replacement side of s///
in Perl. Look both at the accepted answer and the rebuttal answer.
What you are trying to do is possible with the s///ee
form that performs a double eval
on the right hand string. See perlop quote like operators for more examples.
Be warned that there are security impilcations of eval
and this will not work in taint mode.
Just change from ProgressDialog
to ProgressBar
in a layout:
res/layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
//Your content here
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"
android:indeterminateDrawable="@drawable/progress" >
</ProgressBar>
</RelativeLayout>
src/yourPackage/YourActivity.java
public class YourActivity extends Activity{
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
bar = (ProgressBar) this.findViewById(R.id.progressBar);
new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
@Override
protected void onPreExecute(){
bar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
//my stuff is here
}
@Override
protected void onPostExecute(Void result) {
bar.setVisibility(View.GONE);
}
}
}
drawable/progress.xml This is a custom ProgressBar
that i use to change the default colors.
<?xml version="1.0" encoding="utf-8"?>
<!--
Duration = 1 means that one rotation will be done in 1 second. leave it.
If you want to speed up the rotation, increase duration value.
in example 1080 shows three times faster revolution.
make the value multiply of 360, or the ring animates clunky
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1"
android:toDegrees="360" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="8"
android:useLevel="false" >
<size
android:height="48dip"
android:width="48dip" />
<gradient
android:centerColor="@color/color_preloader_center"
android:centerY="0.50"
android:endColor="@color/color_preloader_end"
android:startColor="@color/color_preloader_start"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Try linux command chsh
.
The detailed command is chsh -s /bin/bash
.
It will prompt you to enter your password.
Your default login shell is /bin/bash
now. You must log out and log back in to see this change.
The following is quoted from man page:
The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account
This command will change the default login shell permanently.
Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh
.
String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());
For me none of the solutions here solved it. Frustrated, I restarted my Macbook's iTerm terminal, and voila! My github authorization started working again.
Weird, but maybe iTerm has its own way of handling SSH authorizations or that my terminal session wasn't authorized somehow.
You can use StreamReader.ReadToEnd()
,
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
$1=""
leaves a space as Ben Jackson mentioned, so use a for
loop:
awk '{for (i=2; i<=NF; i++) print $i}' filename
So if your string was "one two three", the output will be:
two
three
If you want the result in one row, you could do as follows:
awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}' filename
This will give you: "two three"
Someone over at Ozgrid answered a similar question. Basically, you just copy each sheet one at a time from Workbook1 to Workbook2.
Sub CopyWorkbook()
Dim currentSheet as Worksheet
Dim sheetIndex as Integer
sheetIndex = 1
For Each currentSheet in Worksheets
Windows("SOURCE WORKBOOK").Activate
currentSheet.Select
currentSheet.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(sheetIndex)
sheetIndex = sheetIndex + 1
Next currentSheet
End Sub
Disclaimer: I haven't tried this code out and instead just adopted the linked example to your problem. If nothing else, it should lead you towards your intended solution.
Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:
wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
echo "Sorry you are Offline"
exit 1
fi
Notice how instead of -ne
, you can just use !=
. In an arithmetic context, we don't even have to prepend $
to parameters, i.e.,
var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"
works perfectly fine. This doesn't appply to the $?
special parameter, though.
Further, since (( ... ))
evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to
if (( $? )); then
but this might confuse more people than the keystrokes saved are worth.
The (( ... ))
construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).
This all being said, it's better to avoid $?
altogether in my opinion, as in Cole's answer and Steven's answer.
There are a few things you can try to get this working.
Be ABSOLUTELY sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file.
Be sure that you've included the script after you've included jQuery, as it is most certainly dependant upon that.
Other than that, I checked out the API and you're definitely doing everything right as far as I can see. Best of luck friend!
EDIT: Ensure you close your script tag. There's an answer below that points to that being the solution.
I assume you're trying to tunnel into some unix box.
Make sure X11 forwarding is enabled in your PuTTY settings.
This is how you can nest multiple bool queries in one outer bool query this using Kibana,
GET my_inedx/my_type/_search
{
"query" : {
"bool": { //bool indicates we are using boolean operator
"must" : [ //must is for **AND**
{
"match" : {
"description" : "some text"
}
},
{
"match" :{
"type" : "some Type"
}
},
{
"bool" : { //here its a nested boolean query
"should" : [ //should is for **OR**
{
"match" : {
//ur query
}
},
{
"match" : {}
}
]
}
}
]
}
}
}
This is how you can nest a query in ES
There are more types in "bool" like,
EasyGUI for very easy GUI Development
If you need to disable the team for now, as you don't have a development account, just change the target at the top menu to iPhone instead of generic iOS device or real device.
To literally fix your example you would use this:
Sub Normalize()
Dim Ticker As Range
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Sheets("Sheet2").Select
Cells(1, 1).PasteSpecial xlPasteAll
End Sub
To Make slight improvments on it would be to get rid of the Select and Activates:
Sub Normalize()
With Sheets("Sheet1")
.Range(.Cells(2, 1), .Cells(65, 1)).Copy Sheets("Sheet2").Cells(1, 1)
End With
End Sub
but using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.
Sub Normalize()
Dim CopyFrom As Range
Set CopyFrom = Sheets("Sheet1").Range("A2", [A65])
Sheets("Sheet2").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
End Sub
To define the CopyFrom
you can use anything you want to define the range, You could use Range("A2:A65")
, Range("A2",[A65])
, Range("A2", "A65")
all would be valid entries. also if the A2:A65 Will never change the code could be further simplified to:
Sub Normalize()
Sheets("Sheet2").Range("A1:A65").Value = Sheets("Sheet1").Range("A2:A66").Value
End Sub
I added the Copy from range, and the Resize
property to make it slightly more dynamic in case you had other ranges you wanted to use in the future.
One case worth mentioning: when connecting from Node.js to Node.js using Express, I get "socket hang up" if I don't prefix the requested URL path with "/".
You can create several divs and do that:
<div style="width:100px; height:100px;">
<div style="position:relative; top:0px; left:0px; width:100px; height:100px; opacity:0.3;"><img src="urltoimage" alt=" " /></div>
<div style="position:relative; top:0px; left:0px; width:100px; height:100px;"> DIV with no opacity </div>
</div>
I did that couple times... Simple, yet effective...
Way late to the game but I imagine this may be helpful to someone. The majority of people tend to measure month to month by date excluding the fact that months come in different variations. Using that frame of thought I created a one liner which compares the dates for us. Using the the following process.
If the end year is not greater we perform the same as 2A/2B, but without adding the 12 months because we do not need to evaluate around the year.
DateTime date = new DateTime(2003, 11, 25);
DateTime today = new DateTime(2004, 12, 26);
var time = (today.Year - date.Year > 1 ? (today.Year - date.Year - 1) * 12 : 0) + (today.Year > date.Year ? (today.Day >= date.Day ? today.Month + 12 - date.Month : today.Month + 12 - (date.Month + 1)) : (today.Day >= date.Day ? today.Month - date.Month : today.Month - (date.Month + 1)));
To perform an HTTP PUT:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
To perform an HTTP DELETE:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
You can use
document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)
or
document.getElementById("parentID").innerHTML+= "new content"
If you are using Git Extensions: go into the Commit screen, there should be a checkbox that says "Amend Commit" at the bottom, as can be seen below:
It's there because all controls in ASP .NET inherit from System.Web.UI.Control which has the "runat" attribute.
in the class System.Web.UI.HTMLControl, the attribute is not required, however, in the class System.Web.UI.WebControl the attribute is required.
edit: let me be more specific. since asp.net is pretty much an abstract of HTML, the compiler needs some sort of directive so that it knows that specific tag needs to run server-side. if that attribute wasn't there then is wouldn't know to process it on the server first. if it isn't there it assumes it is regular markup and passes it to the client.
This example shows how to go directly to the Windows API and not link in the C Standard Library.
global _main
extern _GetStdHandle@4
extern _WriteFile@20
extern _ExitProcess@4
section .text
_main:
; DWORD bytes;
mov ebp, esp
sub esp, 4
; hStdOut = GetstdHandle( STD_OUTPUT_HANDLE)
push -11
call _GetStdHandle@4
mov ebx, eax
; WriteFile( hstdOut, message, length(message), &bytes, 0);
push 0
lea eax, [ebp-4]
push eax
push (message_end - message)
push message
push ebx
call _WriteFile@20
; ExitProcess(0)
push 0
call _ExitProcess@4
; never here
hlt
message:
db 'Hello, World', 10
message_end:
To compile, you'll need NASM and LINK.EXE (from Visual studio Standard Edition)
nasm -fwin32 hello.asm link /subsystem:console /nodefaultlib /entry:main hello.obj
Add the class constraint as the first constraint to your generic type.
static T FindThing<T>(IList collection, int id) where T : class, IThing, new()
I agree with all other posters that say "don't do that" or "SQL isn't good at that". If you want to sort by some facet of comments then add another integer column to one of your tables to hold your sort criteria and sort by that value. eg "ORDER BY comments.sort DESC " If you want to sort these in a different order every time then... SQL won't be for you in this case.
In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:
$ curl https://api.twitter.com/1/help/configuration.xml | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool
Tested on Ubuntu 11.0.4/11.10.
Another issue is the desired content type. Twitter uses .xml
/.json
extension, but more idiomatic REST would require Accept
header:
$ curl -H "Accept: application/json"
The CP1 means 'Code Page 1' - technically this translates to code page 1252
Adobe Acrobat has a very cool but rather well hidden mode allowing you to inspect PDF files. I wrote a blog article explaining it at https://blog.idrsolutions.com/2009/04/viewing-pdf-objects/
This is just a thought. There is one very easy way to do it. If you just need number of words and not actual words then just use Apache WordUtils
import org.apache.commons.lang.WordUtils;
public class CountWord {
public static void main(String[] args) {
String str = "Just keep a boolean flag around that lets you know if the previous character was whitespace or not pseudocode follows";
String initials = WordUtils.initials(str);
System.out.println(initials);
//so number of words in your file will be
System.out.println(initials.length());
}
}
First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:
var data : {
name: string;
file: File;
} = {
name: "Name",
file: inputValue.files[0]
};
Then you send it to the Server with JSON.stringify(data)
let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);
It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.
Another option is the openxlsx
-package. It doesn't depend on java and can read, edit and write Excel-files. From the description from the package:
openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java
Example usage:
library(openxlsx)
# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')
# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')
Besides these two basic functions, the openxlsx
-package has a host of other functions for manipulating Excel-files.
For example, with the writeDataTable
-function you can create formatted tables in an Excel-file.
Having been recently bitten by the FP bug reading many wonderful accounts of how neatly the functional paradigm fits with Javascript
I replicate the code for completeness sake and suggest two ways this can be done functionally.
var carBrands = [];
var car1 = {name:'ford'};
var car2 = {name:'lexus'};
var car3 = {name:'maserati'};
var car4 = {name:'ford'};
var car5 = {name:'toyota'};
carBrands.push(car1);
carBrands.push(car2);
carBrands.push(car3);
carBrands.push(car4);
// ES6 approach which uses the includes method (Chrome47+, Firefox43+)
carBrands.includes(car1) // -> true
carBrands.includes(car5) // -> false
If you need to support older browsers use the polyfill, it seems IE9+ and Edge do NOT support it. Located in polyfill section of MSDN page
Alternatively I would like to propose an updated answer to cdhowie
// ES2015 syntax
function containsObject(obj, list) {
return list.some(function(elem) {
return elem === obj
})
}
// or ES6+ syntax with cool fat arrows
function containsObject(obj, list) {
return list.some(elem => elem === obj)
}
I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.
function newTab(url)
{
var tab=window.open("");
tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
tab.document.close();
window.location.href=url;
}
Fiddle : http://jsfiddle.net/tFCnA/show/
Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)
The only thing you may doesn't like is that the new tab opens before the main page.
you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.
Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html
FYI for everyone's information
This would have been an appropriate solution to resolve the following error
Received HTTP code 407 from proxy after CONNECT
So the following commands should be necessary
git config --global http.proxyAuthMethod 'basic'
git config --global https.proxy http://user:pass@proxyserver:port
Which would generate the following config
$ cat ~/.gitconfig
[http]
proxy = http://user:pass@proxyserver:port
proxyAuthMethod = basic
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
In Firefox, these function behave quite differently: log
only prints out a toString
representation, whereas dir
prints out a navigable tree.
In Chrome, log
already prints out a tree -- most of the time. However, Chrome's log
still stringifies certain classes of objects, even if they have properties. Perhaps the clearest example of a difference is a regular expression:
> console.log(/foo/);
/foo/
> console.dir(/foo/);
* /foo/
global: false
ignoreCase: false
lastIndex: 0
...
You can also see a clear difference with arrays (e.g., console.dir([1,2,3])
) which are log
ged differently from normal objects:
> console.log([1,2,3])
[1, 2, 3]
> console.dir([1,2,3])
* Array[3]
0: 1
1: 2
2: 3
length: 3
* __proto__: Array[0]
concat: function concat() { [native code] }
constructor: function Array() { [native code] }
entries: function entries() { [native code] }
...
DOM objects also exhibit differing behavior, as noted on another answer.
As per Atmocreation's solution, except you don't need to re-checkout the whole project, which is useful if you have existing work in progress.
Let's say you have a working copy:
/foo/
which contains directories:
/foo/bar/baz
and you're getting the error message on commit:
svn: File already exists: filesystem '/foo/bar'
Backup the contents of bar somewhere:
mkdir -p ~/tmp/code_backup
cp -r /foo/bar ~/tmp/code_backup
Delete the .svn control directories from the backup. Make sure you get this command right, or you can do pretty serious damage!! Delete them manually if you're unsure.
find ~/tmp/code_backup/bar -name .svn -type d -exec rm -rf {} \;
Double check that the copy is identical:
diff -r -x .svn dist ~/tmp/code_backup/dist
Remove the offending directory from the working copy: cd /foo rm -rf bar
And then restore it from the repository:
cd /foo
svn update bar
Copy back the modified files from backup:
cp -r ~/tmp/code_backup/bar /foo/
You should now be able to commit without the error.
You can do request.env['REQUEST_URI']
to see the full requested URI.. it will output something like below
http://localhost:3000/client/1/users/1?name=test
Use Bat To Exe Converter
Create a batch file and put something like the code below into it
%extd% /download http://www.examplesite.com/file.zip file.zip
or
%extd% /download http://stackoverflow.com/questions/4619088/windows-batch-file-file-download-from-a-url thistopic.html
and convert it to exe.
Use Access's VBA function Replace(text, find, replacement)
:
Dim result As String
result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")
The objdump
tool can tell you this information. If you invoke objdump
with the -x
option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".
For example running objdump -x /usr/lib/libXpm.so.4
on my system gives the following information in the "Dynamic Section":
Dynamic Section:
NEEDED libX11.so.6
NEEDED libc.so.6
SONAME libXpm.so.4
INIT 0x0000000000002450
FINI 0x000000000000e0e8
GNU_HASH 0x00000000000001f0
STRTAB 0x00000000000011a8
SYMTAB 0x0000000000000470
STRSZ 0x0000000000000813
SYMENT 0x0000000000000018
PLTGOT 0x000000000020ffe8
PLTRELSZ 0x00000000000005e8
PLTREL 0x0000000000000007
JMPREL 0x0000000000001e68
RELA 0x0000000000001b38
RELASZ 0x0000000000000330
RELAENT 0x0000000000000018
VERNEED 0x0000000000001ad8
VERNEEDNUM 0x0000000000000001
VERSYM 0x00000000000019bc
RELACOUNT 0x000000000000001b
The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4
on my system just needs libX11.so.6
and libc.so.6
.
It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump
will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.
you can implement your adapter's onClickListener:
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener
and use interface with method in it
public interface mClickListener {
public void mClick(View v, int position);
}
and in your onClick method call the method in the interface and pass it the view and position
in your main activity implement that interface
public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener
and override that method
@Override
public void onCommentsClick(View v, int position) {
final Intent intent = new Intent(this, OtherActivity.class);
}
as its better to manage your activity transition by the activity not other classes
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray
with java8 Stream API.
import org.json.JSONArray;
import org.json.JSONObject;
@Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });
i find that this works for me
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
The following approach worked for me:
Create a new personal access token in GitHub and configure the connection in IntelliJ as per link: https://www.jetbrains.com/help/idea/github.html
Then, on IntelliJ, Settings-Version Control-Git screen, unclick the "Use credential helper" option.
Then do an restart with cache invalidation (File - Invalidate Caches / Restart - Invalidate and Restart)
export FORCE_BUNDLING=true
worked for me. There was a warning in the console that it was not getting bundled.
I also have the same need but that works with JPA 2.0 and Hibernate 5.0.2:
SELECT p FROM MatchProfile p WHERE CONCAT(p.id, '') = :keyword
Works wonders. I think it works with LIKE too.
It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore
file:
# intellij configs
.idea/
For those of you using python3 you can use:
python3 setup.py install
Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance
f = open('{}.csv'.format(name), 'wb')
Another option - the f-string formatting (ref):
f = open(f"{name}.csv", 'wb')
The root cause is: your environment variable LC_ALL
is missing or invalid somehow
Short answer-
just run the following command:
$ export LC_ALL=C
If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc
file.
Long answer-
Here is my locale
settings:
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C
Python2.7
$ uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
$ python --version
Python 2.7.9
$ pip --version
pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
$ unset LC_ALL
$ pip install virtualenv
Traceback (most recent call last):
File "/usr/local/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
locale.setlocale(locale.LC_ALL, '')
File "/usr/lib/python2.7/locale.py", line 579, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
$ export LC_ALL=C
$ pip install virtualenv
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
If you want to merge the filters (eg. CSV and Excel files), use this formula:
OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";
Or if you want to see XML or PDF files in one time use this:
of.Filter = @" XML or PDF |*.xml;*.pdf";
If you are using a Toolbar as the ActionBar,
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then just use the layout_height of the toolbar.
int actionBarHeight = toolbar.getLayoutParams().height;
You need to get 2 folders back from your css file.
Try:
background-image: url("../../images/image.png");
Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here
So here is the main html file :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
Iframe = $('#frame1');
Iframe.on('load', function(){
IframeInner = Iframe.contents().find('iframe');
IframeInnerClone = IframeInner.clone();
IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});
IframeInnerClone.on('load', function(){
IframeContents = IframeInner.contents();
YourNestedEl = IframeContents.find('div');
$('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
});
});
});
</script>
</head>
<body>
<div id="insertIframeAfter">Hello!!!!</div>
<iframe id="frame1" src="Test_Iframe.html">
</iframe>
</body>
</html>
As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.
Here is the Test_Iframe.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>Test_Iframe</div>
<iframe src="Test_Iframe2.html">
</iframe>
</body>
</html>
and the Test_Iframe2.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>I am the second nested iframe</div>
</body>
</html>
For boxes that does not have internet access, you can remove epel
repository:
yum remove epel-release --disablerepo=epel
This happened to me as I accidentally installed epel-release
using rpm
on a prod box.
In the spirit of itertools. Inspiration from the pairwise recipe.
from itertools import tee, izip
def average(iterable):
"s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
a, b = tee(iterable)
next(b, None)
return ((x+y)/2.0 for x, y in izip(a, b))
Examples:
>>>list(average([1,2,3,4,5]))
[1.5, 2.5, 3.5, 4.5]
>>>list(average([1,20,31,45,56,0,0]))
[10.5, 25.5, 38.0, 50.5, 28.0, 0.0]
>>>list(average(average([1,2,3,4,5])))
[2.0, 3.0, 4.0]
In short: the web server issues a unique identifier to each visitor on his first visit. The visitor must bring back that ID for him to be recognised next time around. This identifier also allows the server to properly segregate objects owned by one session against that of another.
If load-on-startup is false:
If load-on-startup is true:
Once he's on the service mode and on the groove, the same servlet will work on the requests from all other clients.
Why isn't it a good idea to have one instance per client? Think about this: Will you hire one pizza guy for every order that came? Do that and you'd be out of business in no time.
It comes with a small risk though. Remember: this single guy holds all the order information in his pocket: so if you're not cautious about thread safety on servlets, he may end up giving the wrong order to a certain client.
Ctrl++
or
Ctrl+=
Ctrl+-
This feature is described here:
In text editors, you can now use Zoom In (Ctrl++ or Ctrl+=) and Zoom Out (Ctrl+-) commands to increase and decrease the font size. Like a change in the General > Appearance > Colors and Fonts preference page, the commands persistently change the font size in all editors of the same type. If the editor type's font is configured to use a default font, then that default font will be zoomed.
So, the font size change is not limited to the current file and the new value of the font size is available here Window > Preferences > General > Appearance > Colors and Fonts.
Here is all you need:
curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers
i've try a lot of ways, but only this work for me
thanks for workaround
check your .env
MYSQL_VERSION=latest
then type this command
$ docker-compose exec mysql bash
$ mysql -u root -p
(login as root)
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'secret';
then go to phpmyadmin and login as :
hope it help
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
AsyncTask is very helpful!
class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
private Activity activity;
private ProgressDialog dialog;
private Context context;
public QueryBibleDetail(Activity activity){
this.activity = activity;
this.context = activity;
this.dialog = new ProgressDialog(activity);
this.dialog.setTitle("????");
this.dialog.setMessage("????:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
if(!this.dialog.isShowing()){
this.dialog.show();
}
}
@Override
protected String doInBackground(Integer... params) {
Log.d(TAG,"??doInBackground");
publishProgress(params[0]);
if(sectionFromID > sectionToID){
return "";
}
String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
try{
String bible = (Json.getRequest(HOST+queryBible)).trim();
bible = android.text.Html.fromHtml(bible).toString();
return bible;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String bible){
Log.d(TAG,"??onPostExecute");
TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
bibleBox.setText(bible);
this.dialog.dismiss();
}
}
This simple technique will allow the makefile to function normally when forcing is not desired. Create a new target called force at the end of your makefile. The force target will touch a file that your default target depends on. In the example below, I have added touch myprogram.cpp. I also added a recursive call to make. This will cause the default target to get made every time you type make force.
yourProgram: yourProgram.cpp
g++ -o yourProgram yourProgram.cpp
force:
touch yourProgram.cpp
make
What most answers here don't explain is - what if you need to make columns visible again and invisible, all based on data dynamically? After all, shouldn't GridViews
be data centric?
What if you want to turn ON or OFF columns based on your data?
My Gridview
<asp:GridView ID="gvLocationBoard" runat="server" AllowPaging="True" AllowSorting="True" ShowFooter="false" ShowHeader="true" Visible="true" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None"
DataSourceID="sdsLocationBoard" OnDataBound="gvLocationBoard_DataBound" OnRowDataBound="gvLocationBoard_RowDataBound" PageSize="15" OnPreRender="gvLocationBoard_PreRender">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="StudentID" SortExpression="StudentID" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student" SortExpression="StudentName">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("StudentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="CheckStatusName" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HiddenField ID="hfStatusID" runat="server" Value='<%# Eval("CheckStatusID") %>' />
<asp:Label ID="Label4" runat="server" Text='<%# Eval("CheckStatusName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollCallPeriod0" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="cbRollCallPeriod0" runat="server" />
<asp:HiddenField ID="hfRollCallPeriod0" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
</ItemTemplate>
<HeaderStyle Font-Size="Small" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="RollCallPeriod1" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="cbRollCallPeriod1" runat="server" />
<asp:HiddenField ID="hfRollCallPeriod1" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
</ItemTemplate>
<HeaderStyle Font-Size="Small" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
..
etc..
Note the `"RollCallPeriodn", where 'n' is a sequential number.
The way I do it, is to by design hide all columns that I know are going to be ON (visible="true") or OFF (visible="false") later, and depending on my data.
In my case I want to display Period Times up to a certain column. So for example, if today is 9am then I want to show periods 6am, 7am, 8am and 9am, but not 10am, 11am, etc.
On other days I want to show ALL the times. And so on.
So how do we do this?
Why not use PreRender
to "reset" the Gridview
?
protected void gvLocationBoard_PreRender(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
int wsPos = 3;
for (int wsCol = 0; wsCol < 19; wsCol++)
{
gv.Columns[wsCol + wsPos].HeaderText = "RollCallPeriod" + wsCol.ToString("{0,00}");
gv.Columns[wsCol + wsPos].Visible = false;
}
}
Now turn ON the columns you need based on finding the Start of the HeaderText and make the column visible if the header text is not the default.
protected void gvLocationBoard_DataBound(object sender, EventArgs e)
{
//Show the headers for the Period Times directly from sdsRollCallPeriods
DataSourceSelectArguments dss = new DataSourceSelectArguments();
DataView dv = sdsRollCallPeriods.Select(dss) as DataView;
DataTable dt = dv.ToTable() as DataTable;
if (dt != null)
{
int wsPos = 0;
int wsCol = 3; //start of PeriodTimes column in gvLocationBoard
foreach (DataRow dr in dt.Rows)
{
gvLocationBoard.Columns[wsCol + wsPos].HeaderText = dr.ItemArray[1].ToString();
gvLocationBoard.Columns[wsCol + wsPos].Visible = !gvLocationBoard.Columns[wsCol + wsPos].HeaderText.StartsWith("RollCallPeriod");
wsPos += 1;
}
}
}
I won't reveal the SqlDataSource
here, but suffice to say with the PreRender
, I can reset my GridView
and turn ON the columns I want with the headers I want.
So the way it works is that everytime you select a different date or time periods to display as headers, it resets the GridView to the default header text and Visible="false" status before it builds the gridview
again. Otherwise, without the PreRender
, the GridView will have the previous data's headers as the code behind wipes the default settings.
In addition to given answer, it's worth noting that compiler is not required to initialize constexpr
variable at compile time, knowing that the difference between constexpr
and static constexpr
is that to use static constexpr
you ensure the variable is initialized only once.
Following code demonstrates how constexpr
variable is initialized multiple times (with same value though), while static constexpr
is surely initialized only once.
In addition the code compares the advantage of constexpr
against const
in combination with static
.
#include <iostream>
#include <string>
#include <cassert>
#include <sstream>
const short const_short = 0;
constexpr short constexpr_short = 0;
// print only last 3 address value numbers
const short addr_offset = 3;
// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
// determine initial size of strings
std::string title = "value \\ address of ";
const size_t ref_size = ref_name.size();
const size_t title_size = title.size();
assert(title_size > ref_size);
// create title (resize)
title.append(ref_name);
title.append(" is ");
title.append(title_size - ref_size, ' ');
// extract last 'offset' values from address
std::stringstream addr;
addr << param;
const std::string addr_str = addr.str();
const size_t addr_size = addr_str.size();
assert(addr_size - offset > 0);
// print title / ref value / address at offset
std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}
// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
static short temp = const_short;
const short const_var = ++temp;
print_properties("const", &const_var, addr_offset);
if (counter)
const_value(counter - 1);
}
// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
static short temp = const_short;
static short static_var = ++temp;
print_properties("static", &static_var, addr_offset);
if (counter)
static_value(counter - 1);
}
// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
static short temp = const_short;
static const short static_var = ++temp;
print_properties("static const", &static_var, addr_offset);
if (counter)
static_const_value(counter - 1);
}
// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
constexpr short constexpr_var = constexpr_short;
print_properties("constexpr", &constexpr_var, addr_offset);
if (counter)
constexpr_value(counter - 1);
}
// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
static constexpr short static_constexpr_var = constexpr_short;
print_properties("static constexpr", &static_constexpr_var, addr_offset);
if (counter)
static_constexpr_value(counter - 1);
}
// final test call this method from main()
void test_static_const()
{
constexpr short counter = 2;
const_value(counter);
std::cout << std::endl;
static_value(counter);
std::cout << std::endl;
static_const_value(counter);
std::cout << std::endl;
constexpr_value(counter);
std::cout << std::endl;
static_constexpr_value(counter);
std::cout << std::endl;
}
Possible program output:
value \ address of const is 1 564
value \ address of const is 2 3D4
value \ address of const is 3 244
value \ address of static is 1 C58
value \ address of static is 1 C58
value \ address of static is 1 C58
value \ address of static const is 1 C64
value \ address of static const is 1 C64
value \ address of static const is 1 C64
value \ address of constexpr is 0 564
value \ address of constexpr is 0 3D4
value \ address of constexpr is 0 244
value \ address of static constexpr is 0 EA0
value \ address of static constexpr is 0 EA0
value \ address of static constexpr is 0 EA0
As you can see yourself constexpr
is initilized multiple times (address is not the same) while static
keyword ensures that initialization is performed only once.
iOS 4.3.2's User Agent, which came out this week, is:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5
read
reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.
Consequently, the following code is not safe if the input might not be terminated by a newline:
while read LINE; do
# do something with LINE
done
because the body of the while
won't be executed on the last line.
Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.
One way to solve the problem is to test if what was read is non-empty (-n
):
while read -r LINE || [[ -n $LINE ]]; do
# do something with LINE
done
Other solutions include using mapfile
to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep .
, for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk
(which is usually my preference).
Note that -r
is almost certainly needed in the read
builtin; it causes read
to not reinterpret \
-sequences in the input.
Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration
. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow.
To provide an example :
@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
@Configuration
static class ContextConfiguration{
// ... you beans here used in test flow
@Bean
public MockMvc mockMvc() {
return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
.addFilters(/*optionally filters*/).build();
}
//Defined a mocked bean
@Bean
public MyService myMockedService() {
return Mockito.mock(MyService.class);
}
}
@Autowired
private MockMvc mockMvc;
@Autowired
MyService myMockedService;
@Before
public void setup(){
//mock your methods from MyService bean
when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);
}
@Test
public void test(){
//test your controller which trigger the method from MyService
MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
// do your asserts to verify
}
}
If you want the image to load and display a particular image, then use .src
to load that image URL.
If you want a piece of meta data (on any tag) that can contain a URL, then use data-src
or any data-xxx
that you want to select.
MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
Example of src
on an image tag where the image loads the JPEG for you and displays it:
<img id="myImage" src="http://mydomain.com/foo.jpg">
<script>
var imageUrl = document.getElementById("myImage").src;
</script>
Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:
<div id="myDiv" data-src="http://mydomain.com/foo.jpg">
<script>
// in all browsers
var imageUrl = document.getElementById("myDiv").getAttribute("data-src");
// or in modern browsers
var imageUrl = document.getElementById("myDiv").dataset.src;
</script>
Example of data-src
on an image tag used as a place to store the URL of an alternate image:
<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">
<script>
var item = document.getElementById("myImage");
// switch the image to the URL specified in data-src
item.src = item.dataset.src;
</script>
using from ListSelectionModel
:
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
You can put this in your .h file for your class and define it as property, in XCode 7:
@property int (*stuffILike) [10];
Put your div inside another div, apply the border to the outer div with n amount of padding/margin where n is the space you want between them.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
The true problem here may be if you have a 32-bit system. MongoDB 3.X was never made to be used on a 32-bit system, so the repostories for 32-bit is empty (hence why it is not found). Installing the default 2.X Ubuntu package might be your best bet with:
sudo apt-get install -y mongodb
Another workaround, if you nevertheless want to get the latest version of Mongo:
You can go to https://www.mongodb.org/downloads and use the drop-down to select "Linux 32-bit legacy"
But it comes with severe limitations...
This 32-bit legacy distribution does not include SSL encryption and is limited to around 2GB of data. In general you should use the 64 bit builds. See here for more information.
If you store an object in session state, that object must be serializable.
edit:
In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.
You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.
To perform a request with a cookie attached just do the following:
var requestify = require('requestify');
requestify.post('http://google.com', {}, {
cookies: {
sessionCookie: 'session-cookie-data'
}
});
The error says that there is a mismatch, assuming that you have a common contract based on the same WSDL, then the mismatch is in the configuration.
For example that the client is using nettcpip and the server is set up to use basic http.
In my case, Global Settings matters.
After I changed my global network setting with DHCP Servers on, I could start my genymotion virtual device.
I blogged it. http://okjsp.tistory.com/1165644212 (sorry for korean, but you can see it from images)
If you have a SOCK_STREAM
socket, recv
just gets "up to the first 3000 bytes" from the stream. There is no clear guidance on how big to make the buffer: the only time you know how big a stream is, is when it's all done;-).
If you have a SOCK_DGRAM
socket, and the datagram is larger than the buffer, recv
fills the buffer with the first part of the datagram, returns -1, and sets errno to EMSGSIZE. Unfortunately, if the protocol is UDP, this means the rest of the datagram is lost -- part of why UDP is called an unreliable protocol (I know that there are reliable datagram protocols but they aren't very popular -- I couldn't name one in the TCP/IP family, despite knowing the latter pretty well;-).
To grow a buffer dynamically, allocate it initially with malloc
and use realloc
as needed. But that won't help you with recv
from a UDP source, alas.
You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
+-- __init__.py
+-- moduleB.py
In moduleB
:
from toplevel_package import moduleA
If you'd like to run moduleB.py
as a script then make sure that parent directory for toplevel_package
is in your sys.path
.
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
Because:
$ find /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home -name java*
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javac
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javadoc
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javafxpackager
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javah
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javap
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javapackager
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/javafx-src.zip
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/java
It's an array, so ==== ''
won't work (the === means it has to be an empty string.)
Use count() to identify the array has any elements (count returns a number, 1 or greater will evaluate to true, 0 = false.)
@if (count($status->replies) > 0)
// your HTML + foreach loop
@endif
From your referenced page:
http://googlecode.blogspot.com/2009/12/google-analytics-launches-asynchronous.html
Firefox 3.6 is the first browser to officially offer support for this new feature. If you're curious, here are more details on the official HTML5 async specification.
<script type="text/javascript">
$(document).ready(function(){
$(".scroll-element").click(function(){
$('html,body').animate({
scrollTop: $('.our_companies').offset().top
}, 1000);
return false;
});
})
</script>
I would recommend making your life easier by using this library for background works:
https://github.com/Arasthel/AsyncJobLibrary
It's this simple...
AsyncJob.doInBackground(new AsyncJob.OnBackgroundJob() {
@Override
public void doOnBackground() {
startRecording();
}
});
private T GetHeaderControl<T>(Repeater rp, string id) where T : Control
{
T returnValue = null;
if (rp != null && !String.IsNullOrWhiteSpace(id))
{
returnValue = rp.Controls.Cast<RepeaterItem>().Where(i => i.ItemType == ListItemType.Header).Select(h => h.FindControl(id) as T).Where(c => c != null).FirstOrDefault();
}
return returnValue;
}
Finds and casts the control. (Based on Piyey's VB answer)
I just had the same problem, and none of the suggestions above worked. Finally I tried unchecking "Atomic soft tabs" in the Editor Settings menu, which worked.
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests
so PHP code like:
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
will need replace to PHP code
curl_setopt($ch, CURLOPT_URL, $url_page);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $url_page);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
//if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
May be some body reply how this options connected with "Curl error: Operation timed out after .."
Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the urn:uuid: URN scheme, and in CORBA).
I'm super late to the party, but this doesn't appear in any of the existing answers:
GROUP BY DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', date_column) / 10 * 10, '2000')
10
and MINUTE
terms can be changed to any number and DATEPART
, respectively.DATETIME
value, which means:
SELECT
statement will give your output a column with pretty output truncated at the level you specify.'2000'
is an "anchor date" around which SQL will perform the date math. Jereonh discovered below that you encounter an integer overflow with the previous anchor (0
) when you group recent dates by seconds or milliseconds.†SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', aa.[date]) / 10 * 10, '2000')
AS [date_truncated],
COUNT(*) AS [records_in_interval],
AVG(aa.[value]) AS [average_value]
FROM [friib].[dbo].[archive_analog] AS aa
GROUP BY DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', aa.[date]) / 10 * 10, '2000')
ORDER BY [date_truncated]
If your data spans centuries,‡ using a single anchor date for second- or millisecond grouping will still encounter the overflow. If that is happening, you can ask each row to anchor the binning comparison to its own date's midnight:
Use DATEADD(DAY, DATEDIFF(DAY, 0, aa.[date]), 0)
instead of '2000'
wherever it appears above. Your query will be totally unreadable, but it will work.
An alternative might be CONVERT(DATETIME, CONVERT(DATE, aa.[date]))
as the replacement.
† 232 ˜ 4.29E+9, so if your DATEPART
is SECOND
, you get 4.3 billion seconds on either side, or "anchor ± 136 years." Similarly, 232 milliseconds is ˜ 49.7 days.
‡ If your data actually spans centuries or millenia and is still accurate to the second or millisecond… congratulations! Whatever you're doing, keep doing it.
copy this line and replace in your project
var myNewString = myOldString.replace ("username", visitorName);
there is a simple problem with coma (,)
You can access characters in strings in the same way as you would access an array index, e.g.
$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
$thisWordCodeVerdeeld[$i] = $string[$i];
}
You could also do:
$thisWordCodeVerdeeld = str_split($string);
However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.
Especially for the older Git versions, most of the suggestions won't work that well. If that's the case, I'd put a separate .gitignore in the directory where I want the content to be included regardless of other settings and allow there what is needed.
For example: /.gitignore
# ignore all .dll files
*.dll
/dependency_files/.gitignore
# include everything
!*
So everything in /dependency_files (even .dll files) are included just fine.
You can manually insert http header to request:
HttpGet request = new HttpGet(...);
request.setHeader("Authorization", "Basic "+Base64.encodeBytes("login:password".getBytes()));
In case you want to use it for copy protection and you need it to return always the same serial on one computer (of course as far as first hdd or ssd is not changed) I would recommend code below. For ManagementClass you need to add reference to System.Management. P.S. Without "InterfaceType" and "DeviceID" check that method can return serial of random disk or serial of USB flash drive which connected to pc right now.
public static string GetSerial()
{
try
{
var mc = new ManagementClass("Win32_DiskDrive");
var moc = mc.GetInstances();
var res = string.Empty;
var resList = new List<string>(moc.Count);
foreach (ManagementObject mo in moc)
{
try
{
if (mo["InterfaceType"].ToString().Replace(" ", string.Empty) == "USB")
{
continue;
}
}
catch
{
}
try
{
res = mo["SerialNumber"].ToString().Replace(" ", string.Empty);
resList.Add(res);
if (mo["DeviceID"].ToString().Replace(" ", string.Empty).Contains("0"))
{
if (!string.IsNullOrWhiteSpace(res))
{
return res;
}
}
}
catch
{
}
}
res = resList[0];
if (!string.IsNullOrWhiteSpace(res))
{
return res;
}
}
catch
{
}
return string.Empty;
}
Android Studio:
Eclipse:
Find the MissingTranslation
line, and set it to Warning
as seen below:
In the command prompt, type the command below and press Enter.
bcdedit /enum
Under the Windows Boot Loader sections, make note of the identifier value.
To start in safe mode from command prompt :
bcdedit /set {identifier} safeboot minimal
Then enter the command line to reboot your computer.
Add the image to Your project by clicking File -> "Add Files to ...".
Then choose the image in ImageView properties (Utilities -> Attributes Inspector).
Use the object tag:
<object data="http://iamawesome.com" type="text/html" width="200" height="200">
<a href="http://iamawesome.com">access the page directly</a>
</object>
Ref: http://debug.ga/embedding-external-pages-without-iframes/
in your hosting.json
replace"Url": "http://localhost:80"
by"Url": "http://*:80"
and you will be able now access to your application by http://your_local_machine_ip:80
for example http://192.168.1.4:80
Construct it with a list instead of a dictionary
frame = pd.DataFrame([
[1, .1, 'a'],
[2, .2, 'e'],
[3, 1, 'i'],
[4, 4, 'o']
], columns=['one thing', 'second thing', 'other thing'])
frame
one thing second thing other thing
0 1 0.1 a
1 2 0.2 e
2 3 1.0 i
3 4 4.0 o
Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.
Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .
You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"
If you are using Gradle, you could include the dependency like this:
repositories {
mavenCentral()
}
dependencies {
compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'
}
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
This is the most up-to-date solution.
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="group1" />Check Me
<input type="checkbox" name="chk9[120]" class="group1" />
<input type="checkbox" name="chk9[140]" class="group1" />
<input type="checkbox" name="chk9[150]" class="group1" />
</form>
$(function() {
enable_cb();
$("#group1").click(enable_cb);
});
function enable_cb() {
$("input.group1").prop("disabled", !this.checked);
}
Here is the usage details for .attr()
and .prop()
.
Use the new .prop()
function:
$("input.group1").prop("disabled", true);
$("input.group1").prop("disabled", false);
The .prop()
function is not available, so you need to use .attr()
.
To disable the checkbox (by setting the value of the disabled attribute) do
$("input.group1").attr('disabled','disabled');
and for enabling (by removing the attribute entirely) do
$("input.group1").removeAttr('disabled');
If you're working with just one element, it will always be fastest to use DOMElement.disabled = true
. The benefit to using the .prop()
and .attr()
functions is that they will operate on all matched elements.
// Assuming an event handler on a checkbox
if (this.disabled)
Sure, just handle the mousehover event and tell it to display a tool tip. t is a tooltip defined either in the globals or in the constructor using:
ToolTip t = new ToolTip();
then the event handler:
private void control_MouseHover(object sender, EventArgs e)
{
t.Show("Text", (Control)sender);
}
As easy as
SELECT lpad(42::text, 4, '0')
References:
sqlfiddle: http://sqlfiddle.com/#!15/d41d8/3665
I have implemented BasicAuthenticationHandler
for basic authentication so you can use it with standart attributes Authorize
and AllowAnonymous
.
public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authHeader = (string)this.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':', StringComparison.OrdinalIgnoreCase);
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
//you also can use this.Context.Authentication here
if (username == "test" && password == "test")
{
var user = new GenericPrincipal(new GenericIdentity("User"), null);
var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
else
{
return Task.FromResult(AuthenticateResult.Fail("No valid user."));
}
}
this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
return Task.FromResult(AuthenticateResult.Fail("No credentials."));
}
}
public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
public BasicAuthenticationMiddleware(
RequestDelegate next,
IOptions<BasicAuthenticationOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder encoder)
: base(next, options, loggerFactory, encoder)
{
}
protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
{
return new BasicAuthenticationHandler();
}
}
public class BasicAuthenticationOptions : AuthenticationOptions
{
public BasicAuthenticationOptions()
{
AuthenticationScheme = "Basic";
AutomaticAuthenticate = true;
}
}
Registration at Startup.cs - app.UseMiddleware<BasicAuthenticationMiddleware>();
. With this code, you can restrict any controller with standart attribute Autorize:
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller
and use attribute AllowAnonymous
if you apply authorize filter on application level.
If all you really care about is the actual query (the last one run) for quick debugging purposes:
DB::enableQueryLog();
# your laravel query builder goes here
$laQuery = DB::getQueryLog();
$lcWhatYouWant = $laQuery[0]['query']; # <-------
# optionally disable the query log:
DB::disableQueryLog();
do a print_r()
on $laQuery[0]
to get the full query, including the bindings. (the $lcWhatYouWant
variable above will have the variables replaced with ??
)
If you're using something other than the main mysql connection, you'll need to use these instead:
DB::connection("mysql2")->enableQueryLog();
DB::connection("mysql2")->getQueryLog();
(with your connection name where "mysql2" is)
Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.
https://tools.percona.com/wizard
Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/
Everyone points to key_buffer_size
first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).
As per current versions, Android doesn't ask for permission to interact with the internet but you can add the below code which will help for users using older versions Just add these in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
(Note 29/08/2017: live
was deprecated many versions ago and removed in v1.9. delegate
was deprecated in v3.0. In both cases, use the delegating signature of on
instead [also covered below].)
live
happens by capturing the event when it's bubbled all the way up the DOM to the document root, and then looking at the source element. click
happens by capturing the event on the element itself. So if you're using live
, and one of the ancestor elements is hooking the event directly (and preventing it continuing to bubble), you'll never see the event on your element. Whereas normally, the element nearest the event (click or whatever) gets first grab at it, the mix of live
and non-live
events can change that in subtle ways.
For example:
jQuery(function($) {_x000D_
_x000D_
$('span').live('click', function() {_x000D_
display("<tt>live</tt> caught a click!");_x000D_
});_x000D_
_x000D_
$('#catcher').click(function() {_x000D_
display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
function display(msg) {_x000D_
$("<p>").html(msg).appendTo(document.body);_x000D_
}_x000D_
_x000D_
});
_x000D_
<div>_x000D_
<span>Click me</span>_x000D_
<span>or me</span>_x000D_
<span>or me</span>_x000D_
<div>_x000D_
<span>I'm two levels in</span>_x000D_
<span>so am I</span>_x000D_
</div>_x000D_
<div id='catcher'>_x000D_
<span>I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span>me too</span>_x000D_
</div>_x000D_
</div>_x000D_
<!-- Using an old version because `live` was removed in v1.9 -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">_x000D_
</script>
_x000D_
I'd recommend using delegate
over live
when you can, so you can more thoroughly control the scope; with delegate
, you control the root element that captures the bubbling event (e.g., live
is basically delegate
using the document root as the root). Also, recommend avoiding (where possible) having delegate
or live
interacting with non-delegated, non-live event handling.
Here several years later, you wouldn't use either live
or delegate
; you'd use the delegating signature of on
, but the concept is still the same: The event is hooked on the element you call on
on, but then fired only when descendants match the selector given after the event name:
jQuery(function($) {_x000D_
_x000D_
$(document).on('click', 'span', function() {_x000D_
display("<tt>live</tt> caught a click!");_x000D_
});_x000D_
_x000D_
$('#catcher').click(function() {_x000D_
display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
return false;_x000D_
});_x000D_
_x000D_
function display(msg) {_x000D_
$("<p>").html(msg).appendTo(document.body);_x000D_
}_x000D_
_x000D_
});
_x000D_
<div>_x000D_
<span>Click me</span>_x000D_
<span>or me</span>_x000D_
<span>or me</span>_x000D_
<div>_x000D_
<span>I'm two levels in</span>_x000D_
<span>so am I</span>_x000D_
</div>_x000D_
<div id='catcher'>_x000D_
<span>I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
<span>me too</span>_x000D_
</div>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Setting the CLASSPATH System Variable
To display the current CLASSPATH variable, use these commands in Windows and UNIX (Bourne shell):
In Windows: C:\> set CLASSPATH
In UNIX: % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use these commands:
In Windows: C:\> set CLASSPATH=
In UNIX: % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable, use these commands (for example):
In Windows: C:\> set CLASSPATH=C:\users\george\java\classes
In UNIX: % CLASSPATH=/home/george/java/classes; export CLASSPATH
Addition to @jwize's answer
Because angular.element(document).injector()
was giving error injector is not defined
So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.
function compileAngularElement( elSelector) {
var elSelector = (typeof elSelector == 'string') ? elSelector : null ;
// The new element to be added
if (elSelector != null ) {
var $div = $( elSelector );
// The parent of the new element
var $target = $("[ng-app]");
angular.element($target).injector().invoke(['$compile', function ($compile) {
var $scope = angular.element($target).scope();
$compile($div)($scope);
// Finally, refresh the watch expressions in the new element
$scope.$apply();
}]);
}
}
use it by passing just new element's selector. like this
compileAngularElement( '.user' ) ;
Here is a more generalized solution that prints all elements of x the vector x in this format:
x=randperm(3);
s = repmat('%d,',1,length(x));
s(end)=[]; %Remove trailing comma
disp(sprintf(['Answer: (' s ')'], x))
Use os.walk
with next
item function:
next(os.walk('.'))[1]
For Python <=2.5 use:
os.walk('.').next()[1]
os.walk
is a generator and calling next
will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the [1]
index returns only the dirnames
from that tuple.
This simple function recursively merges JSON objects, please notice that this function merges all JSON into first param (target
), if you need new object modify this code.
var mergeJSON = function (target, add) {
function isObject(obj) {
if (typeof obj == "object") {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return true; // search for first object prop
}
}
}
return false;
}
for (var key in add) {
if (add.hasOwnProperty(key)) {
if (target[key] && isObject(target[key]) && isObject(add[key])) {
this.mergeJSON(target[key], add[key]);
} else {
target[key] = add[key];
}
}
}
return target;
};
BTW instead of isObject()
function may be used condition like this:
JSON.stringify(add[key])[0] == "{"
but this is not good solution, because it's will take a lot of resources if we have large JSON objects.
How about less /var/log/syslog
?
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
I found it in this location:
C:\Users\amitsinha02\AppData\Local\Android\sdk\platform-tools
I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:
user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$
As a bash function (which you could add to your ~/.bashrc):
function mvn-there() {
DIR="$1"
shift
(cd $DIR; mvn "$@")
}
user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$
I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.
Regards
Passing an array of items as a collapsed parameter to the WHERE..IN clause will fail since query will take form of WHERE Age IN ("11, 13, 14, 16")
.
But you can pass your parameter as an array serialized to XML or JSON:
nodes()
method:StringBuilder sb = new StringBuilder();
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
sb.Append("<age>" + item.Text + "</age>"); // actually it's xml-ish
sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
SELECT Tab.col.value('.', 'int') as Age from @Ages.nodes('/age') as Tab(col))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = sb.ToString();
OPENXML
method:using System.Xml.Linq;
...
XElement xml = new XElement("Ages");
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
xml.Add(new XElement("age", item.Text);
sqlComm.CommandText = @"DECLARE @idoc int;
EXEC sp_xml_preparedocument @idoc OUTPUT, @Ages;
SELECT * from TableA WHERE Age IN (
SELECT Age from OPENXML(@idoc, '/Ages/age') with (Age int 'text()')
EXEC sp_xml_removedocument @idoc";
sqlComm.Parameters.Add("@Ages", SqlDbType.Xml);
sqlComm.Parameters["@Ages"].Value = xml.ToString();
That's a bit more on the SQL side and you need a proper XML (with root).
OPENJSON
method (SQL Server 2016+):using Newtonsoft.Json;
...
List<string> ages = new List<string>();
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
ages.Add(item.Text);
sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
select value from OPENJSON(@Ages))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = JsonConvert.SerializeObject(ages);
Note that for the last method you also need to have Compatibility Level at 130+.
The following code returns the wanted "folder" as Path regardless of if it is inside a jar or not.
private Path getFolderPath() throws URISyntaxException, IOException {
URI uri = getClass().getClassLoader().getResource("folder").toURI();
if ("jar".equals(uri.getScheme())) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
return fileSystem.getPath("path/to/folder/inside/jar");
} else {
return Paths.get(uri);
}
}
Requires java 7+.
A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants
@IntDef({NOTAX, SALESTAX, IMPORTEDTAX})
@interface TAX {}
int NOTAX = 0;
int SALESTAX = 10;
int IMPORTEDTAX = 5;
Use as function parameter:
void computeTax(@TAX int taxPercentage){...}
or in a variable declaration:
@TAX int currentTax = IMPORTEDTAX;
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
I have solved the problem by just move the .mdf file that you want to attach to the public folder, in my case I moved it to the users/public folder. Then I attach it from there without any problem. Hope this helps.
I just had this problem and resolved it by adding the namespace to the service name, e.g.
<service name="TechResponse">
became
<service name="SvcClient.TechResponse">
I've also seen it resolved with a Web.config instead of an App.config.
1) == evaluates reference equality in this case
2) im not too sure about the equals, but why not simply overriding the compare method and plant it inside MyClass?
In general you cannot rely on a fixed pixel size for fonts, the user may be scaling the screen and the defaults are not always the same (depends on DPI settings of the screen etc.).
Maybe have a look at this (pixel to point) and this link.
But of course you can set the font size to px, so that you do know how many pixels the font actually is. This may help if you really need a fixed layout, but this practice reduces accessibility of your web site.
Check the following Function for date comparison first of all create two NSDate objects and pass to the function: Add the bellow lines of code in viewDidload or according to your scenario.
-(void)testDateComaparFunc{
NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}
here is the function
-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{
BOOL isTokonValid;
if ([date1 compare:date2] == NSOrderedDescending) {
//"date1 is later than date2
isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
//date1 is earlier than date2
isTokonValid = NO;
} else {
//dates are the same
isTokonValid = NO;
}
return isTokonValid;}
Simply change the date and test above function :)
Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.
css
thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}
html
<table>
<thead>
<tr><th>hey</th><th>ho</th></tr>
</thead>
<tbody>
<tr><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td></tr>
</tbody>
Try assigning the style of border: 0px; border-collapse: collapse;
to the table element.
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
My favorite version is the inline version:
${"variableName"} = 12;
$className->{"propertyName"};
$className->{"methodName"}();
StaticClass::${"propertyName"};
StaticClass::{"methodName"}();
You can place variables or expressions inside the brackets too!
Internet Explorer versions before IE9 do not support media queries.
If you are looking for a way of degrading the design for IE8 users, you may find IE's conditional commenting helpful. Using this, you can specify an IE 8/7/6 specific style sheet which over writes the previous rules.
For example:
<link rel="stylesheet" type="text/css" media="all" href="style.css"/>
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ie.css"/>
<![endif]-->
This won't allow for a responsive design in IE8, but could be a simpler and more accessible solution than using a JS plugin.
session_cache_expire( 20 );
session_start(); // NEVER FORGET TO START THE SESSION!!!
$inactive = 1200; //20 minutes *60
if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
header("Location: user_logout.php");
}
}
$_SESSION['start'] = time();
if($_SESSION['valid_user'] != true){
header('Location: ../....php');
}else{
source: http://www.daniweb.com/web-development/php/threads/124500
Use the substring method of the String class :
String removeCurrency=amount.getText().toString().substring(3);
A stream is a continuous flow of liquid, air, or gas.
Java stream is a flow of data from a source into a destination. The source or destination can be a disk, memory, socket, or other programs. The data can be bytes, characters, or objects. The same applies for C# or C++ streams. A good metaphor for Java streams is water flowing from a tap into a bathtub and later into a drainage.
The data represents the static part of the stream; the read and write methods the dynamic part of the stream.
InputStream
represents a flow of data from the source, the OutputStream
represents a flow of data into the destination.
Finally, InputStream
and OutputStream
are abstractions over low-level access to data, such as C file pointers.
In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.
DateTime
class , OOP Style.<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m
Update with psycopg2 2.7:
The classic executemany()
is about 60 times slower than @ant32 's implementation (called "folded") as explained in this thread: https://www.postgresql.org/message-id/20170130215151.GA7081%40deb76.aryehleib.com
This implementation was added to psycopg2 in version 2.7 and is called execute_values()
:
from psycopg2.extras import execute_values
execute_values(cur,
"INSERT INTO test (id, v1, v2) VALUES %s",
[(1, 2, 3), (4, 5, 6), (7, 8, 9)])
Previous Answer:
To insert multiple rows, using the multirow VALUES
syntax with execute()
is about 10x faster than using psycopg2 executemany()
. Indeed, executemany()
just runs many individual INSERT
statements.
@ant32 's code works perfectly in Python 2. But in Python 3, cursor.mogrify()
returns bytes, cursor.execute()
takes either bytes or strings, and ','.join()
expects str
instance.
So in Python 3 you may need to modify @ant32 's code, by adding .decode('utf-8')
:
args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x).decode('utf-8') for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)
Or by using bytes (with b''
or b""
) only:
args_bytes = b','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute(b"INSERT INTO table VALUES " + args_bytes)
delete: delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
splice: actually removes the element, reindexes the array, and changes its length.
Delete element from last
arrName.pop();
Delete element from first
arrName.shift();
Delete from middle
arrName.splice(starting index,number of element you wnt to delete);
Ex: arrName.splice(1,1);
Delete one element from last
arrName.splice(-1);
Delete by using array index number
delete arrName[1];
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
///*
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK && null != data){
uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(prjection[0]);
ImagePath = cursor.getString(columnIndex);
cursor.close();
FixBitmap = BitmapFactory.decodeFile(ImagePath);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
// FixBitmap = new BitmapDrawable(ImagePath);
int nh = (int) ( FixBitmap.getHeight() * (512.0 / FixBitmap.getWidth()) );
FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true);
// ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
This code is work
In my case, the HTML was laid out like this:
<div class="share">
<div class="wrapper">
<div class="share">
</div>
</div>
</div>
And my jQuery was like this:
jQuery('.share').toggle();
It confused me because nothing appeared to be happening. The problem was that the inner .share
s toggle
would cancel out the outer .share
s toggle
.
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
For a matrix you can use this:
[M,I] = max(A(:))
I is the index of A(:) containing the largest element.
Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.
[I_row, I_col] = ind2sub(size(A),I)
I am also looking for similar feature "list all resources" in AWS but could not find anything good enough.
"Resource Groups" does not help because it only list resources which have been tagged and user have to specify the tag. If you miss to tag a resource, that won't appear in "Resource Groups" .
UI of "Create a resource group"
A more suitable feature is "Resource Groups"->"Tag Editor" as already mentioned in the previous post. Select region(s) and resource type(s) to see listing of resources in Tag editor. This serves the purpose but not very user-friendly because I have to enter region and resource type every time I want to use it. I am still looking for easy to use UI.
I modified the code as follow:
ViewModel
using System.Collections.Generic;
using ContosoUniversity.Models;
namespace ContosoUniversity.ViewModels
{
public class InstructorIndexData
{
public PagedList.IPagedList<Instructor> Instructors { get; set; }
public PagedList.IPagedList<Course> Courses { get; set; }
public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
}
}
Controller
public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
int instructPageNumber = (InstructorPage?? 1);
int CoursePageNumber = (CoursePage?? 1);
int EnrollmentPageNumber = (EnrollmentPage?? 1);
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
viewModel.Enrollments = viewModel.Courses.Where(
x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
}
return View(viewModel);
}
View
<div>
Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount
@Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))
</div>
I hope this would help you!!
Although side_effect
can achieve the goal, it is not so convenient to setup side_effect
function for each test case.
I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:
from nextmock import Mock
m = Mock()
m.with_args(1, 2, 3).returns(123)
assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123
It also supports argument matcher:
from nextmock import Arg, Mock
m = Mock()
m.with_args(1, 2, Arg.Any).returns(123)
assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123
Hope this package could make testing more pleasant. Feel free to give any feedback.
Use CSS:
<html>
<head>
<style>
.Large
{
font-size: 16pt;
height: 50px;
}
</style>
<body>
<input type="text" class="Large">
</body>
</html>
For me it helped to add ?$query_string
at the end of /index.php, like below:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
If all you're doing is keeping a boolean isEven
then you can consider checking if a class isEven
is on the element then toggling that class.
Using a shared variable like count is kind of bad practice. Ask yourself what is the scope of that variable, think of if you had 10 items that you'd want to toggle on your page, would you create 10 variables, or an array or variables to store their state? Probably not.
Edit:
jQuery has a switchClass method that, when combined with hasClass can be used to animate between the two width you have defined. This is favourable because you can change these sizes later in your stylesheet or add other parameters, like background-color or margin, to transition.
For Visual Studio for Mac users (e.g. who installed Android SDK together with VS):
You can find JDK, Android NDK and Android SDK localizations there (if installed and selected). If no Android SDK path found, you may try to find it using Android Studio (if it is installed)
You could be using the 32 bit version, so you should prob try at the command line from the Framework (not Framework64) folder.
IE Did you try it from C:\Windows\Microsoft.NET\Framework\v4.0.30319 rather than the 64 version? If you ref 32 bit libs you can be forced to 32 bit version (some other reasons as well if I recall)
Is your site a child of another site in IIS?
For more details on this (since it applies to various types of apps running on .NET) see Scott's post at:
32-bit and 64-bit confusion around x86 and x64 and the .NET Framework and CLR
When I run into such problem, I find FUSLOGVW tool very helpful. It is checking assembly binding information and logs it for you. Sometimes the libraries are missing, sometimes GAC has different versions that are being loaded. Sometimes the platform of referenced libraries is causing the problems. This tool makes it clear how the dependencies' bindings are being resolved and this may really help you to investigate/debug your problem.
Fusion Log Viewer / fuslogvw / Assembly Binding Log Viewer. Check more/download here: http://msdn.microsoft.com/en-us/library/e74a18c4.aspx.
What I use:
set long 50000
set linesize 130
col x format a80 word_wrapped;
select dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA') x from dual;
Or am I missing something?
It's hard to respond to a statement without examples of how it's not working, but it's crucial to understand that TFVC (in "Server Workspace" mode, which was the mechanism prior to TFS 2012) does not examine the state of your local filesystem. TFVC Server Workspaces are a "checkout-edit-checkin" type of system where this is by-design, an intentional decision made to massively reduce the amount of file I/O required to determine the state of your workspace. Instead, the workspace information is saved on the server.
This allows TFVC Server Workspaces to scale to very large codebases very efficiently. If you are in a multi-gigabyte code base (like Visual Studio or the Windows source tree) then your client does not need to scan your local filesystem, looking for files that may have changed, because the contract you have with TFS is that you will explicitly check a file out when you want to edit it.
You are expected to not mark a file as write-only and change it without explicitly checking it out first. If you go down this route, then the server does not know that you have made changes to your file, and performing a "Get Latest" operation will not update your local workspace, because you haven't told the server that you've made changes.
If you do subvert this mechanism then you can use the tfpt reconcile
command to examine your local workspace for changes that you have made locally.
If you find yourself using "Get Specific Version" and selecting the "force" and "overwrite" options, then it is very likely that you are in the habit of bypassing all of the enforcements that TFS has implemented to keep you from hurting yourself, and you should probably consider TFVC Local Workspaces.
TFVC Local Workspaces provide an "edit-merge-commit" type of version control system, which means that you do not need to explicitly check files out before editing them and they are not read-only on-disk. Instead, you simply need to edit the file, and your client will scan the filesystem, notice the change, and present this as a pending change.
TFVC Local Workspaces are recommended for small projects that do not require fine-grained permissions control, since they present a much nicer workflow. You are not required to be online, and you do not have to explicitly check files out before editing them.
TFVC Local Workspaces are the default in TFS 2012, and if they are not enabled for you, then you should ask your server administrator. (Organizations with very large codebases or strict auditing requirements may disable TFVC Local Workspaces.)
Eric Sink's excellent book Version Control By Example outlines the differences between checkout-edit-checkin and edit-merge-commit systems and when one is more appropriate than the other.
The Professional Team Foundation Server 2013 book also provides excellent information about the differences between TFVC Server Workspaces and TFVC Local Workspaces. The MSDN documentation and blogs also provide detailed information:
1) gitdir=$(git rev-parse --git-dir);
2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/
a) I don't know how to execute step 1 in windows so skipped it and used hardcoded path in step 2 scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg .git/hooks/
b) In case you get below error, manually create "hooks" directory in .git folder
protocol error: expected control record
c) if you have submodule let's say "XX" then you need to repeat step 2 there as well and this time replace ${gitdir} with that submodules path
d) In case scp is not recognized by windows give full path of scp
"C:\Program Files\Git\usr\bin\scp.exe"
e) .git folder is present in your project repo and it's hidden folder
There is angular service written angular file server Uses FileSaver.js and Blob.js
vm.download = function(text) {
var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(data, 'text.txt');
};
The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).
I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.
On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
url ='http://www.test.com/page/TEST2'.split('/')[4]
print url
Output: TEST2
.
JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null
)
You could create your own toJson
method, only passing the data that really has to be serialized:
Person.prototype.toJson = function() {
return JSON.stringify({age: this.age});
};
Similar for deserializing:
Person.fromJson = function(json) {
var data = JSON.parse(json); // Parsing the json string.
return new Person(data.age);
};
The usage would be:
var serialize = p1.toJson();
var _p1 = Person.fromJson(serialize);
alert("Is old: " + _p1.isOld());
To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special "data" property for each Person
instance. For example:
function Person(age) {
this.data = {
age: age
};
this.isOld = function (){
return this.data.age > 60 ? true : false;
}
}
then serializing and deserializing is merely calling JSON.stringify(this.data)
and setting the data of an instance would be instance.data = JSON.parse(json)
.
This would keep the toJson
and fromJson
methods simple but you'd have to adjust your other functions.
Side note:
You should add the isOld
method to the prototype of the function:
Person.prototype.isOld = function() {}
Otherwise, every instance has it's own instance of that function which also increases memory.
More correct create DTO for API queries, for example entityDTO:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityDto> getAll() { return entityService.getAllEntities(); }
But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getOneParameterMap() { return ResponseEntity.status(HttpStatus.CREATED).body( Collections.singletonMap("key", "value")); }
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getSomeParameters() { return ResponseEntity.status(HttpStatus.OK).body(Map.of( "key-1", "value-1", "key-2", "value-2", "key-3", "value-3")); }
add one ArrayList to second ArrayList as:
Arraylist1.addAll(Arraylist2);
EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:
ArrayList<String> arraylist3=new ArrayList<String>();
arraylist3.addAll(Arraylist1); // add first arraylist
arraylist3.addAll(Arraylist2); // add Second arraylist
You can use the following. In this case of last character it's an overkill but for a substring, its useful:
var word = "linto.yahoo.com.";
var last = ".com.";
if (word.substr(-(last.length)) == last)
alert("its a match");
This will do want you want, and avoid collisions
static string SanitiseFilename(string key)
{
var invalidChars = Path.GetInvalidFileNameChars();
var sb = new StringBuilder();
foreach (var c in key)
{
var invalidCharIndex = -1;
for (var i = 0; i < invalidChars.Length; i++)
{
if (c == invalidChars[i])
{
invalidCharIndex = i;
}
}
if (invalidCharIndex > -1)
{
sb.Append("_").Append(invalidCharIndex);
continue;
}
if (c == '_')
{
sb.Append("__");
continue;
}
sb.Append(c);
}
return sb.ToString();
}
My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.
HTML:
<div id="zoom_here">....</div>
JS
<script>
var dist1=0;
function start(ev) {
if (ev.targetTouches.length == 2) {//check if two fingers touched screen
dist1 = Math.hypot( //get rough estimate of distance between two fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
}
}
function move(ev) {
if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
// Check if the two target touches are the same ones that started
var dist2 = Math.hypot(//get rough estimate of new distance between fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
//alert(dist);
if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
alert('zoom out');
}
if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
alert('zoom in');
}
}
}
document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>
uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
Simple and not time consuming answer with an example relevant to the question asked Follow this example:
user = [{"name": "Dough", "age": 55},
{"name": "Ben", "age": 44},
{"name": "Citrus", "age": 33},
{"name": "Abdullah", "age":22},
]
print(sorted(user, key=lambda el: el["name"]))
print(sorted(user, key= lambda y: y["age"]))
Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code
print(sorted(user, key=lambda el: el["name"]))
Results to:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Ben', 'age': 44},
{'name': 'Citrus', 'age': 33},
{'name': 'Dough', 'age': 55}]
sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.
The second print code
print(sorted(user, key= lambda y: y["age"]))
Result:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Citrus', 'age': 33},
{'name': 'Ben', 'age': 44},
{'name': 'Dough', 'age': 55}]
sorts by age, and hence the list returns by ascending order of age.
Try this code for better understanding.
When I tried '.* in windows (Notepad ++) it would match everything after first ' until end of last line.
To capture everything until end of that line I typed the following:
'.*?\n
This would only capture everything from ' until end of that line.
There are only two ways to find a web page: through a link or by listing the directory.
Usually, web servers disable directory listing, so if there is really no link to the page, then it cannot be found.
BUT: information about the page may get out in ways you don't expect. For example, if a user with Google Toolbar visits your page, then Google may know about the page, and it can appear in its index. That will be a link to your page.
Do this for a cool border
and font
effect:
#ck-button:hover { /*ADD :hover */
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid red; /*change border color*/
overflow:auto;
float:left;
color:red; /*add font color*/
}
Example: http://jsfiddle.net/zAFND/6/
I don't think ansible will let you specify a password in the flags as you wish to do. There may be somewhere in the configs this can be set but this would make using ansible less secure overall and would not be recommended.
One thing you can do is to create a user on the target machine and grant them passwordless sudo privileges to either all commands or a restricted list of commands.
If you run sudo visudo
and enter a line like the below, then the user 'privilegedUser' should not have to enter a password when they run something like sudo service xxxx start
:
%privilegedUser ALL= NOPASSWD: /usr/bin/service
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.
https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress
Real Time Output Issue resolved:
I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout);
in my C code. It worked for me. Here is the code.
C program:
#include <stdio.h>
void main()
{
int count = 1;
while (1)
{
printf(" Count %d\n", count++);
fflush(stdout);
sleep(1);
}
}
Python program:
#!/usr/bin/python
import os, sys
import subprocess
procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
while procExe.poll() is None:
line = procExe.stdout.readline()
print("Print:" + line)
Output:
Print: Count 1
Print: Count 2
Print: Count 3
For Eclipse
A good way to add external JARs to your Android project or any Java project is:
libs
in your project's root folderlibs
folderNow right click on the Jar file and then select Build Path > Add to Build Path, which will create a folder called 'Referenced Libraries' within your project
By doing this, you will not lose your libraries that are being referenced on your hard drive whenever you transfer your project to another computer.
For Android Studio
Please Note : If you are using 3rd party libraries then it is better to use transitive dependencies where Gradle script automatically downloads the JAR and the dependency JAR when gradle script run.
Ex : compile 'com.google.android.gms:play-services-ads:9.4.0'
Read more about Gradle Dependency Mangement
If you're looking for an inliner for Node.js...
console.log("%o", object);
Its simple way
>>import json
>>from collection import OrderedDict
>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))
Use shell=True
if you're passing a string to subprocess.call
.
From docs:
If passing a single string, either
shell
must beTrue
or else the string must simply name the program to be executed without specifying any arguments.
subprocess.call(crop, shell=True)
or:
import shlex
subprocess.call(shlex.split(crop))
#!/bin/bash
req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"
something like so might work:
<script type="text/javascript">
$(document).ready(function(){
var $input = $("<input name='myField' type='text'>");
$('#section2').append($input);
});
</script>
<form>
<div id="section1"><!-- some controls--></div>
<div id="section2"><!-- for dynamic controls--></div>
</form>
For Pip 8.1.2 you can use pip download -r requ.txt
to download packages to your local machine.
Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:
$.each(myOptions, function(val, text) {
$("#mySelect").append($("<option/>").attr("value", val).text(text));
});