tracert
/traceroute
to find number of hopsThe new HTTP Client shipped with Java 9 but as part of an Incubator module named
jdk.incubator.httpclient
. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.
In Java 9, you can send a GET
request like:
// GET
HttpResponse response = HttpRequest
.create(new URI("http://www.stackoverflow.com"))
.headers("Foo", "foovalue", "Bar", "barvalue")
.GET()
.response();
Then you can examine the returned HttpResponse
:
int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());
Since this new HTTP Client is in java.httpclient
jdk.incubator.httpclient
module, you should declare this dependency in your module-info.java
file:
module com.foo.bar {
requires jdk.incubator.httpclient;
}
click link get example file upload clint java with apache HttpComponents
and library downalod link
https://hc.apache.org/downloads.cgi
use 4.5.3.zip it's working fine in my code
and my working code..
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");
FileBody bin = new FileBody(new File("E:\\meter.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
HTTP status code 500 usually means that the webserver code has crashed. You need to determine the status code beforehand using HttpURLConnection#getResponseCode()
and in case of errors, read the HttpURLConnection#getErrorStream()
instead. It may namely contain information about the problem.
If the host has blocked you, you would rather have gotten a 4nn status code like 401 or 403.
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
May you have taken permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
BUT
multipart/form-data
encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded
encoding. When using a different encoding, the request.getParameter()
calls will all return null
. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts()
instead. Also see this blog for extended examples.
Prior to Servlet 3.0, a de facto standard to parse multipart/form-data
requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).
You can manually force disconnection by a Thread sleep. This is an example:
URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();
then
public class InterruptThread implements Runnable {
HttpURLConnection con;
public InterruptThread(HttpURLConnection con) {
this.con = con;
}
public void run() {
try {
Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
} catch (InterruptedException e) {
}
con.disconnect();
System.out.println("Timer thread forcing to quit connection");
}
}
Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().
http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection
If you are simply after a pretty solution and don't need to save a few nanoseconds, how about some LINQ sugar?
var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };
var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
Something like this will do it:
Rows("12:12").Select
Selection.Delete
So in your code it would look like something like this:
Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete
Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.
After you run the install file SQLExpr.exe
look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)
After that, find the file sqlncli_x64.msi
in the setup folder, and run it.
Now you are ready the run the setup.exe
file and install SQL server 2005 without errors
Please read the other answers and comments, there’s a lot more information stated and nuances described (hash functions?) that I did not know when I answered this question.
According to Jenkins' own help (the "?" button) for the schedule task, 5 fields are specified:
This field follows the syntax of cron (with minor differences). Specifically, each line consists of 5 fields separated by TAB or whitespace: MINUTE HOUR DOM MONTH DOW
I just tried to get a job to launch at 4:42PM (my approximate local time) and it worked with the following, though it took about 30 extra seconds:
42 16 * * *
If you want multiple times, I think the following should work:
0 16,18,20,22 * * *
for 4, 6, 8, and 10 o'clock PM every day.
SQL> create table a(id number);
Table created.
SQL> alter table a rename column id to new_id;
Table altered.
SQL> desc a
Name Null? Type
----------------------------------------- -------- -----------
NEW_ID NUMBER
command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])
You can run npx webpack
. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package.
Source of info: https://webpack.js.org/guides/getting-started/
here is generic swipe left detector for any view in kotlin using databinding
@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
setOnTouchListener(object : View.OnTouchListener {
var x0 = 0F; var y0 = 0F; var t0 = 0L
val defaultClickDuration = 200
override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
motionEvent?.let { event ->
when(event.action) {
MotionEvent.ACTION_DOWN -> {
x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
}
MotionEvent.ACTION_UP -> {
val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()
if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
performClick()
return false
}
if (x0 > x1) { runnable.run() }
}
else -> {}
}
}
return true
}
})
}
and then to use it in your layout:
app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"
I was experiencing this issue and it was driving me nuts; I ultimately found the following lying in my POM.xml, which was the cause of the problem:
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.
A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.
By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!
If only the incoming stream stalls for more than a millisecond you are running into a timeout.
Disabled HTML forms elements aren't sent along with the post/get values when you submit the form. So if you disable your submit button once clicked and that this submit button have the name
attribute set, It will not be sent in the post/get values since the element is now disabled. This is normal behavior.
One of the way to overcome this problem is using hidden form elements.
You can create an empty DataFrame with either column names or an Index:
In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []
Or
In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Edit: Even after your amendment with the .to_html, I can't reproduce. This:
df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')
Produces:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
<th>G</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Kindly check whether the file name has an extension for example:
abc.csv
if so remove the .csv
extension.
set wd
to the folder containing the file (~)
data<-read.csv("abc.csv")
Your data has been read the data object
You could also try:
<asp:UpdatePanel runat="server" ID="myUpdatePanel">
<ContentTemplate>
<script type="text/javascript" language="javascript">
function pageLoad() {
$('div._Foo').bind("mouseover", function(e) {
// Do something exciting
});
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
,since pageLoad() is an ASP.NET ajax event which is executed each time the page is loaded at client side.
I had same issue, and for me, I was trying to use an IP Address instead of computer name. Just adding this as one more potential solution for people finding this down the road.
Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.
Pros - More flexible than an array.
Cons - You can't pass a string containing a comma.
CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();
list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");
string s = list.ToString(); //Huey,Dewey,Louie
IMO the best way to accomplish your goal is to display a numeric keyboard rather than the normal keyboard. This restricts which keys are available to the user. This alleviates the need to do validation, and more importantly it prevents the user from making a mistake. The number pad is also much nicer for entering numbers because the keys are substantially larger.
In interface builder select the UITextField, go to the Attributes Inspector and change the "Keyboard Type" to "Decimal Pad".
That'll make the keyboard look like this:
The only thing left to do is ensure the user doesn't enter in two decimal places. You can do this while they're editing. Add the following code to your view controller. This code removes a second decimal place as soon as it is entered. It appears to the user as if the 2nd decimal never appeared in the first place.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldDidChange:(UITextField *)textField
{
NSString *text = textField.text;
NSRange range = [text rangeOfString:@"."];
if (range.location != NSNotFound &&
[text hasSuffix:@"."] &&
range.location != (text.length - 1))
{
// There's more than one decimal
textField.text = [text substringToIndex:text.length - 1];
}
}
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Button2_Click(Sender, e)
End Sub
This Code call button click event programmatically
Source Code x bit number
int x =8;
data =15; //input
unsigned char tmp;
for(int i =0;i<x;i++)
{
printf("Data & 1 %d\n",data&1);
printf("Data Shifted value %d\n",data>>1^(data&1)<<(x-1));
tmp = data>>1|(data&1)<<(x-1);
data = tmp;
}
To be precise,
Thread.isAlive()
returns true if the thread has been started (may not yet be running) but has not yet completed its run method.
Thread.getState()
returns the exact state of the thread.
Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!
list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]
Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:
flattened = [val for sublist in list_of_lists for val in sublist]
is equivalent to:
flattened = []
for sublist in list_of_lists:
for val in sublist:
flattened.append(val)
The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!
If you have multiple items in a sublist the list comp will even flatten that. ie
>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened = [val for sublist in list_of_lists for val in sublist]
>>> flattened
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]
Also note that Scala extends String with a number of methods (via implicit conversion to a WrappedString brought in by Predef) so you could also do the following:
val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
Are android:name and class: interchangeable?
Presumably, yes. I have only used class, and that seems to be what most of Google's examples use, but I do see where they use android:name in some samples. Unfortunately, there is no formal and complete documentation for fragment.
use
class = "com.fragment.NavigationDrawerFragment"
insted of
android:name="com.fragment.NavigationDrawerFragment"
That seemingly means that program looks "class" attribute first. And on fail looks "name" attribute. So as far as it's true using "class" if more efficient
Two suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
Specifications:
Articles:
Tutorial:
Libraries:
<script>
var listh = document.getElementById( 'list-home-list' );
var hb = document.getElementsByTagName('hb');
$("#list-home-list").click(function(){
$(this).style.color = '#2C2E33';
hb.style.color = 'white';
});
</script>
It will give you all active sockets on a specific IP:
netstat -an | find "172.20.1.166"
The short answer for this is, "because that's what the C++ standard specifies".
Note that you can always specify a constructor that's different from the default, like so:
class Shape {
Shape() {...} //default constructor
Shape(int h, int w) {....} //some custom constructor
};
class Rectangle : public Shape {
Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call
}
The default constructor of the base class is called only if you don't specify which one to call.
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 }; // Will initialize all elements to 0
int myArray[10] = { 5 }; // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i; // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC
I fixed this by doing the following
git branch --unset-upstream
rm .git/refs/remotes/origin/{branch}
git gc --prune=now
git branch --set-upstream-to=origin/{branch} {branch}
#or git push --set-upstream origin {branch}
git pull
This assuming that your local and remote branches are aligned and you are just getting the refs error as non fatal.
After hours of research this solution worked for me:
(disclaimer: results may vary due to circumstances)
the Library not found -lPods-(someCocoapod)
error was due to multiple entries in the :
Settings(Target) > Build Settings > Linking > 'Other Linker Flags'
A lot of other posts had me look there and I would see changes to the error when I messed around with the entries, but I kept getting some variation on the same error.
Too many hours lost ...
remove the -lPods-(someCocoaPod) lines in the 'Other Linker Flags' list BUT only if $(inherited) is at the top. At first I was unsure, but the reassuring sign was that I still saw references to my cocoapods when I left the edit mode(inherited). I tested in debug and release, both of which were giving me errors, and the problem was immediately resolved.
If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:
position:absolute;
right:0;
top:0;
If you want it to float at the right of a particular parent section, you can add position: relative
to that section.
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists()
with isset()
.
public function hasProperty($property)
{
return property_exists($this, $property) && isset($this->$property);
}
Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.
var width = 960,_x000D_
height = 500,_x000D_
json = {_x000D_
"nodes": [{_x000D_
"x": 100,_x000D_
"r": 20,_x000D_
"label": "Node 1",_x000D_
"color": "red"_x000D_
}, {_x000D_
"x": 200,_x000D_
"r": 25,_x000D_
"label": "Node 2",_x000D_
"color": "blue"_x000D_
}, {_x000D_
"x": 300,_x000D_
"r": 30,_x000D_
"label": "Node 3",_x000D_
"color": "green"_x000D_
}]_x000D_
};_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
.attr("width", width)_x000D_
.attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
.append("pattern")_x000D_
.attr({_x000D_
"id": "stripes",_x000D_
"width": "8",_x000D_
"height": "8",_x000D_
"fill": "red",_x000D_
"patternUnits": "userSpaceOnUse",_x000D_
"patternTransform": "rotate(60)"_x000D_
})_x000D_
.append("rect")_x000D_
.attr({_x000D_
"width": "4",_x000D_
"height": "8",_x000D_
"transform": "translate(0,0)",_x000D_
"fill": "grey"_x000D_
});_x000D_
_x000D_
function plotChart(json) {_x000D_
/* Define the data for the circles */_x000D_
var elem = svg.selectAll("g myCircleText")_x000D_
.data(json.nodes)_x000D_
_x000D_
/*Create and place the "blocks" containing the circle and the text */_x000D_
var elemEnter = elem.enter()_x000D_
.append("g")_x000D_
.attr("class", "node-group")_x000D_
.attr("transform", function(d) {_x000D_
return "translate(" + d.x + ",80)"_x000D_
})_x000D_
_x000D_
/*Create the circle for each block */_x000D_
var circleInner = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", function(d) {_x000D_
return d.color;_x000D_
});_x000D_
_x000D_
var circleOuter = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", "url(#stripes)");_x000D_
_x000D_
/* Create the text for each block */_x000D_
elemEnter.append("text")_x000D_
.text(function(d) {_x000D_
return d.label_x000D_
})_x000D_
.attr({_x000D_
"text-anchor": "middle",_x000D_
"font-size": function(d) {_x000D_
return d.r / ((d.r * 10) / 100);_x000D_
},_x000D_
"dy": function(d) {_x000D_
return d.r / ((d.r * 25) / 100);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
Output:
Below is the link to codepen
also:
Thanks, Manish Kumar
I was able to fix this by deleting node_modules and running npm install again
Next to what has described @Roshith in his answer here:
If you are behind a proxy, set it correctly in npm.
npm config set proxy http://proxyhost:proxyport npm config set https-proxy http://proxyhost:proxyport
I had to change also the the file ~.bashrc
which also contained a worng proxy setting in my case. I changed those settings here:
export HTTP_PROXY="http://proxyhost:proxyport"
export HTTPS_PROXY="http://proxyhost:proxyport"
Use the following command to verify the proxy settings:
env | grep -i proxy
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
Try this https://ngrok.com/docs#expose
Just run ngrok 3000
, 3000
is the port number you want to expose to the internet. You can insert the port number which you want to expose, for rails its 3000. This will tunnel your localhost to the internet and you will be able to view your local host from anywhere
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
Android studio offers you to analyse any apk file.
1 - From build menu choose analyse apk option and select apk file. 2 - This will result in you the classes.dex file and other files. 3 - Click on classes.dex which will give you the list of folders, packages, libraries and files. 4 - From and android studio settings install a plugin called "Dex to Jar" 5 - click on any activity file of your extracted project and choose dex to jar from the build menu.
This will result in you the actual code of your java file.
Cheers.
Try looking here: Best way to get application folder path
To quote from there:
System.IO.Directory.GetCurrentDirectory()
returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).
To add a "local" package to your project, add a folder (for example "package_name"). And put your implementation files in that folder.
src/github.com/GithubUser/myproject/
+-- main.go
+---package_name
+-- whatever_name1.go
+-- whatever_name2.go
In your package main
do this:
import "github.com/GithubUser/myproject/package_name"
Where package_name
is the folder name and it must match the package name used in files whatever_name1.go and whatever_name2.go. In other words all files with a sub-directory should be of the same package.
You can further nest more subdirectories as long as you specify the whole path to the parent folder in the import.
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false
, then you can do this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"
if(mymap[key]) {
println mymap[key]
}
However, if the value could potentially be Groovy-false
, you should use:
if(mymap.containsKey(key)) {
println mymap[key]
}
The easiest solution, though, if you know the value isn't going to be Groovy-false
(or you can ignore that), and want a default value, is like this:
def value = mymap[key] ?: "default"
All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap
(or LinkedHashMap
) design that makes direct key access nearly instantaneous.
Use System.DateTime.Now.ToUniversalTime()
. That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
Explicitly specifying the max_iter
resolves the warning as the default max_iter
is 100. [For Logistic Regression].
logreg = LogisticRegression(max_iter=1000)
May 2018 react-native version 0.55.2
secureTextEntry={true} works
password={true} does not work
To link to a YouTube video so it plays in HD by default, use the following URL:
https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).
If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.
I ran into this issue. Turns out I was including in the template, using the static
template tag, a file that did not exist anymore. A look in the logs showed me the problem.
I guess this is just one of many possible reasons for this kind of error.
Moral of the story: always log errors and always check logs.
An easy way without fixed width:
.myTable tbody{
display:block;
overflow:auto;
height:200px;
width:100%;
}
.myTable thead tr{
display:block;
}
Now, on onLoad, to adjust th widths, just add this jquery script:
$.each($('.myTable tbody tr:nth(0) td'), function(k,v) {
$('.myTable thead th:nth('+k+')').css('width', $(v).css('width'));
});
You can even set a separate right margin for HTML. Under the specified path:
File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)
This is very useful because generally HTML and JS may be usually long in one line than Python. :)
Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home'
) in your URL patterns.
The solution is to update your urls.py
to include the view callable. This means that you have to import the view in your urls.py
. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.
from django.conf.urls import include, url
from django.contrib.auth.views import login
from myapp.views import home, contact
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^contact/$', contact, name='contact'),
url(r'^login/$', login, name='login'),
]
If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from myapp import views as myapp_views
urlpatterns = [
url(r'^$', myapp_views.home, name='home'),
url(r'^contact/$', myapp_views.contact, name='contact'),
url(r'^login/$', auth_views.login, name='login'),
]
Note that we have used as myapp_views
and as auth_views
, which allows us to import the views.py
from multiple apps without them clashing.
See the Django URL dispatcher docs for more information about urlpatterns
.
Improved @haitaka answer, using the key and predicate
function deepSearch (object, key, predicate) {
if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object
for (let i = 0; i < Object.keys(object).length; i++) {
let value = object[Object.keys(object)[i]];
if (typeof value === "object" && value != null) {
let o = deepSearch(object[Object.keys(object)[i]], key, predicate)
if (o != null) return o
}
}
return null
}
So this can be invoked as:
var result = deepSearch(myObject, 'id', (k, v) => v === 1);
or
var result = deepSearch(myObject, 'title', (k, v) => v === 'Some Recommends');
Here is the demo: http://jsfiddle.net/a21dx6c0/
EDITED
In the same way you can find more than one object
function deepSearchItems(object, key, predicate) {
let ret = [];
if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) {
ret = [...ret, object];
}
if (Object.keys(object).length) {
for (let i = 0; i < Object.keys(object).length; i++) {
let value = object[Object.keys(object)[i]];
if (typeof value === "object" && value != null) {
let o = this.deepSearchItems(object[Object.keys(object)[i]], key, predicate);
if (o != null && o instanceof Array) {
ret = [...ret, ...o];
}
}
}
}
return ret;
}
The solution is so easy. Only right click the IMAGE (destination) folder, go to properties, click the permission tab, and change others access to Create and delete files.
For PHP code:
<?php
error_reporting(E_ALL & ~E_NOTICE);
For php.ini
config:
error_reporting = E_ALL & ~E_NOTICE
Both are equivalent. Take a look at the following:
int[] array;
// is equivalent to
int array[];
int var, array[];
// is equivalent to
int var;
int[] array;
int[] array1, array2[];
// is equivalent to
int[] array1;
int[][] array2;
public static int[] getArray()
{
// ..
}
// is equivalent to
public static int getArray()[]
{
// ..
}
By default , maven looks at these folders for java and test classes respectively - src/main/java and src/test/java
When the src is specified with the test classes under source and the scope for junit dependency in pom.xml is mentioned as test - org.unit will not be found by maven.
You would need to use position:relative
or position:absolute
on both the parent and child to use z-index
.
This worked for me best:
$('.alert').on('close.bs.alert', function (e) {
e.preventDefault();
$(this).hide();
});
Those CORS headers do not support *
as value, the only way is to replace *
with this:
Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With
.htaccess
Example (CORS Included):<IfModule mod_headers.c>
Header unset Connection
Header unset Time-Zone
Header unset Keep-Alive
Header unset Access-Control-Allow-Origin
Header unset Access-Control-Allow-Headers
Header unset Access-Control-Expose-Headers
Header unset Access-Control-Allow-Methods
Header unset Access-Control-Allow-Credentials
Header set Connection keep-alive
Header set Time-Zone "Asia/Jerusalem"
Header set Keep-Alive timeout=100,max=500
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
Header set Access-Control-Expose-Headers "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
Header set Access-Control-Allow-Methods "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
Header set Access-Control-Allow-Credentials "true"
Header set DNT "0"
Header set Accept-Ranges "bytes"
Header set Vary "Accept-Encoding"
Header set X-UA-Compatible "IE=edge,chrome=1"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set X-Xss-Protection "1; mode=block"
</IfModule>
Why Access-Control-Allow-Headers
, Access-Control-Expose-Headers
, Access-Control-Allow-Methods
values are super long?
Those do not support the *
syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)
Why do you use Header unset ______
syntax?
GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)
Is it safe for me to use 'as-is'?
Well.. mostly the answer would be YES since the .htaccess
is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods
lines. Also Connection
, Time-Zone
, Keep-Alive
and DNT
, Accept-Ranges
, Vary
, X-UA-Compatible
, X-Frame-Options
, X-Content-Type-Options
and X-Xss-Protection
are just a suggestion I'm using for my online-service.. feel free to remove those too...
taken from my comment above
Use <>
to negate the where clause.
For me It worked with following commands
You can access your host machine with the IP address "10.0.2.2
".
This has been designed in this way by the Android team. So your webserver can perfectly run at localhost and from your Android app you can access it via "http://10.0.2.2:<hostport>
".
If your emulator must access the internet through a proxy server, you can configure a custom HTTP proxy from the emulator's Extended controls screen. With the emulator open, click More , and then click Settings and Proxy. From here, you can define your own HTTP proxy settings.
(Adding to previous answers (hope that helps someone):)
Age is simpler but in case of string and with ignoring case:
@fathers.any? { |father| father[:name].casecmp("john") == 0 }
should work for any case in start or anywhere in the string i.e. for "John"
, "john"
or "JoHn"
and so on.
@fathers.find { |father| father[:name].casecmp("john") == 0 }
@fathers.select { |father| father[:name].casecmp("john") == 0 }
I had this issue today, and for me the problem was that I had allocated too much memory:
-Xmx1024M -XX:MaxPermSize=1024m
Once I reduced the PermGen space, everything worked fine:
-Xmx1024M -XX:MaxPermSize=512m
I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.
This link helped: https://stackoverflow.com/a/11199865/1307104
I edit my command by adding quotes for every parameter like this:
mvn install:install-file "-DgroupId=org.mozilla" "-DartifactId=jss" "-Dversion=4.2.5" "-Dpackaging=jar" "-Dfile=C:\Users\AArmijos\workspace\componentes-1.0.4\deps\jss-4.2.5.jar"
It's worked.
encodeURIComponent() is the way to go.
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
BUT you should keep in mind that there are small differences from php version urlencode()
and as @CMS mentioned, it will not encode every char. Guys at http://phpjs.org/functions/urlencode/ made js equivalent to phpencode()
:
function urlencode(str) {
str = (str + '').toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace('!', '%21')
.replace('\'', '%27')
.replace('(', '%28')
.replace(')', '%29')
.replace('*', '%2A')
.replace('%20', '+');
}
If you want to be able to specify the seed, you just need to replace the calls to getSeconds()
and getMinutes()
. You could pass in an int and use half of it mod 60 for the seconds value and the other half modulo 60 to give you the other part.
That being said, this method looks like garbage. Doing proper random number generation is very hard. The obvious problem with this is that the random number seed is based on seconds and minutes. To guess the seed and recreate your stream of random numbers only requires trying 3600 different second and minute combinations. It also means that there are only 3600 different possible seeds. This is correctable, but I'd be suspicious of this RNG from the start.
If you want to use a better RNG, try the Mersenne Twister. It is a well tested and fairly robust RNG with a huge orbit and excellent performance.
EDIT: I really should be correct and refer to this as a Pseudo Random Number Generator or PRNG.
"Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
--- John von Neumann
<meta http-equiv="refresh" content="600; url=index.php">
600 is the amount of seconds between refresh cycles.
you can use this extension method and call it like this.
DataTable dt = YourList.ToDataTable();
public static DataTable ToDataTable<T>(this List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection propertyDescriptorCollection =
TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
this is the approach that I used:
create pyspark session:
import pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('changeColNames').getOrCreate()
create dataframe:
df = spark.createDataFrame(data = [('Bob', 5.62,'juice'), ('Sue',0.85,'milk')], schema = ["Name", "Amount","Item"])
view df with column names:
df.show()
+----+------+-----+
|Name|Amount| Item|
+----+------+-----+
| Bob| 5.62|juice|
| Sue| 0.85| milk|
+----+------+-----+
create a list with new column names:
newcolnames = ['NameNew','AmountNew','ItemNew']
change the column names of the df:
for c,n in zip(df.columns,newcolnames):
df=df.withColumnRenamed(c,n)
view df with new column names:
df.show()
+-------+---------+-------+
|NameNew|AmountNew|ItemNew|
+-------+---------+-------+
| Bob| 5.62| juice|
| Sue| 0.85| milk|
+-------+---------+-------+
Guys this is really simple.
login via ssh
into your pi
execute
vncserver -geometry 1200x1600
This will generate a new session :1
connect with your vnc client at ipaddress:1
Thats it.
Use the C++ std::sort
function:
#include <algorithm>
using namespace std;
int main()
{
vector<int> v(2000);
sort(v.begin(), v.end());
}
If you are wanting to dynamically grab the hash from URL, this should work: https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
For others that arrive on this page from google:
DataRow also has a function .IsNull("ColumnName")
public DateTime? TestDt;
public Parse(DataRow row)
{
if (!row.IsNull("TEST_DT"))
TestDt = Convert.ToDateTime(row["TEST_DT"]);
}
I used this:
<a href="url/to/delete.asp" onclick="return confirm(' you want to delete?');">Delete</a>
Reading Datetime value From Excel sheet : Try this will be work.
string sDate = (xlRange.Cells[4, 3] as Excel.Range).Value2.ToString();
double date = double.Parse(sDate);
var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");
res = request.GET['paymentid']
will raise a KeyError
if paymentid
is not in the GET data.
Your sample php code checks to see if paymentid
is in the POST data, and sets $payID
to '' otherwise:
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
The equivalent in python is to use the get()
method with a default argument:
payment_id = request.POST.get('payment_id', '')
while debugging, this is what I see in the
response.GET: <QueryDict: {}>
,request.POST: <QueryDict: {}>
It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.
Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.
There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.
I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).
When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.
It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:
<li><span class="foo">some text</span></li>
<li>some other text</li>
Then refer to it the usual way:
li > span.foo {...}
List<int>[] a = new List<int>[100];
You still would have to allocate each individual list in the array before you can use it though:
for (int i = 0; i < a.Length; i++)
a[i] = new List<int>();
Try moving ValueDate
:
select sum(CASE
WHEN ValueDate > @startMonthDate THEN cash
ELSE 0
END)
from Table a
where a.branch = p.branch
and a.transID = p.transID
(reformatted for clarity)
You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.
Another useful tool, and as a MySQL front-end replacement, is Toad for MySQL. Sadly, no longer supported by Quest, but a brilliant IDE for MySQL, with IMPORT and EXPORT wizards, catering for most file types.
Another approach:
public static void main(String[] args) {
String str = "/folder1/folder2/folder3/";
int index = nthOccurrence(str, '/', 3);
System.out.println(index);
}
public static int nthOccurrence(String s, char c, int occurrence) {
return nthOccurrence(s, 0, c, 0, occurrence);
}
public static int nthOccurrence(String s, int from, char c, int curr, int expected) {
final int index = s.indexOf(c, from);
if(index == -1) return -1;
return (curr + 1 == expected) ? index :
nthOccurrence(s, index + 1, c, curr + 1, expected);
}
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
There are two ways to access an inner function. One, instance-level, like you want, another, static level.
You need to call the function on the return from React.render
. See below.
Take a look at ReactJS Statics. Note, however, that a static function cannot access instance-level data, so this
would be undefined
.
var onButtonClick = function () {
//call alertMessage method from the reference of a React Element!
HelloRendered.alertMessage();
//call static alertMessage method from the reference of a React Class!
Hello.alertMessage();
console.log("clicked!");
}
var Hello = React.createClass({
displayName: 'Hello',
statics: {
alertMessage: function () {
alert('static message');
}
},
alertMessage: function () {
alert(this.props.name);
},
render: function () {
return React.createElement("div", null, "Hello ", this.props.name);
}
});
var HelloElement = React.createElement(Hello, {
name: "World"
});
var HelloRendered = React.render(HelloElement, document.getElementById('container'));
Then do HelloRendered.alertMessage()
.
The request object is not the session.
You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from
HttpSession session = request.getSession(true);
Then you can use setAttribute or getAttribute on the session.
A more up to date tutorial on jsp sessions is: http://courses.coreservlets.com/Course-Materials/pdf/csajsp2/08-Session-Tracking.pdf
Little out of date but here is a function you can use!
function calculateAge(birthMonth, birthDay, birthYear) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var calculatedAge = currentYear - birthYear;
if (currentMonth < birthMonth - 1) {
calculatedAge--;
}
if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
calculatedAge--;
}
return calculatedAge;
}
var age = calculateAge(12, 8, 1993);
alert(age);
I also got the same error. I've referred to the below mentioned link and ran this commands
gpg --import fails with no valid OpenPGP data found
gpg --import KEYS
sudo apt-get update
It worked.
I'm using Ubuntu version 12.04
If I read Modules/cStringIO.c
correctly, this should be quite efficient (although somewhat verbose):
from cStringIO import StringIO
def iterbuf(buf):
stri = StringIO(buf)
while True:
nl = stri.readline()
if nl != '':
yield nl.strip()
else:
raise StopIteration
A simple client-side pagination example where data is fetched only once at page loading.
// dummy data_x000D_
const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
{ "req_no": 2, "title": "test2" },_x000D_
{ "req_no": 3, "title": "test3" },_x000D_
{ "req_no": 4, "title": "test4" },_x000D_
{ "req_no": 5, "title": "test5" },_x000D_
{ "req_no": 6, "title": "test6" },_x000D_
{ "req_no": 7, "title": "test7" },_x000D_
{ "req_no": 8, "title": "test8" },_x000D_
{ "req_no": 9, "title": "test9" },_x000D_
{ "req_no": 10, "title": "test10" },_x000D_
{ "req_no": 11, "title": "test11" },_x000D_
{ "req_no": 12, "title": "test12" },_x000D_
{ "req_no": 13, "title": "test13" },_x000D_
{ "req_no": 14, "title": "test14" },_x000D_
{ "req_no": 15, "title": "test15" },_x000D_
{ "req_no": 16, "title": "test16" },_x000D_
{ "req_no": 17, "title": "test17" },_x000D_
{ "req_no": 18, "title": "test18" },_x000D_
{ "req_no": 19, "title": "test19" },_x000D_
{ "req_no": 20, "title": "test20" },_x000D_
{ "req_no": 21, "title": "test21" },_x000D_
{ "req_no": 22, "title": "test22" },_x000D_
{ "req_no": 23, "title": "test23" },_x000D_
{ "req_no": 24, "title": "test24" },_x000D_
{ "req_no": 25, "title": "test25" },_x000D_
{ "req_no": 26, "title": "test26" }];_x000D_
_x000D_
// on page load collect data to load pagination as well as table_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
// At a time maximum allowed pages to be shown in pagination div_x000D_
const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
// hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
function hide_from_beginning(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.nextSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// hide pages from pagination ending if more than pagination_visible_pages_x000D_
function hide_from_end(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.previousSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// load data and style for active page_x000D_
function active_page(element, rows, req_per_page) {_x000D_
var current_page = document.getElementsByClassName('active');_x000D_
var next_link = document.getElementById('next_link');_x000D_
var prev_link = document.getElementById('prev_link');_x000D_
var next_tab = current_page[0].nextSibling; _x000D_
var prev_tab = current_page[0].previousSibling;_x000D_
current_page[0].className = current_page[0].className.replace("active", "");_x000D_
if (element === "next") {_x000D_
if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
next_tab.previousSibling.className += " active";_x000D_
next_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
next_tab.className += " active"_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_tab.style.display === "none") {_x000D_
next_tab.style.display = "block";_x000D_
hide_from_beginning(prev_link.nextSibling)_x000D_
}_x000D_
}_x000D_
} else if (element === "prev") {_x000D_
if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
prev_tab.nextSibling.className += " active";_x000D_
prev_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
prev_tab.className += " active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (prev_tab.style.display === "none") {_x000D_
prev_tab.style.display = "block";_x000D_
hide_from_end(next_link.previousSibling)_x000D_
}_x000D_
}_x000D_
} else {_x000D_
element.className += "active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// Render the table's row in table request-table_x000D_
function render_table_rows(rows, req_per_page, page_no) {_x000D_
const response = JSON.parse(window.atob(rows));_x000D_
const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
$('#request-table').empty()_x000D_
$('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
resp.forEach(function (element, index) {_x000D_
if (Object.keys(element).length > 0) {_x000D_
const { req_no, title } = element;_x000D_
const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
$('#request-table').append(td)_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Pagination logic implementation_x000D_
function pagination(data, myarr) {_x000D_
const all_data = window.btoa(JSON.stringify(myarr));_x000D_
$(".pagination").empty();_x000D_
if (data.req_per_page !== 'ALL') {_x000D_
let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>«</a>` +_x000D_
`<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
if (total_page < pagination_visible_pages) {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= total_page; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
} else {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
}_x000D_
pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>»</a>`;_x000D_
$(".pagination").append(pager);_x000D_
} else {_x000D_
render_table_rows(all_data, myarr.length, 1);_x000D_
}_x000D_
}_x000D_
_x000D_
//calling pagination function_x000D_
pagination(data, myarr);_x000D_
_x000D_
_x000D_
// trigger when requests per page dropdown changes_x000D_
function filter_requests() {_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
pagination(data, myarr);_x000D_
}
_x000D_
.box {_x000D_
float: left;_x000D_
padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
margin: 5px 0px 0px 0px;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
color: black;_x000D_
float: left;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
transition: background-color .3s;_x000D_
border: 1px solid #ddd;_x000D_
margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<table id="request-table">_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
<div class="box options">_x000D_
<label>Requests Per Page: </label>_x000D_
<select id="req_per_page" onchange="filter_requests()">_x000D_
<option>5</option>_x000D_
<option>10</option>_x000D_
<option>ALL</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="box pagination">_x000D_
</div>_x000D_
</div>
_x000D_
you do not need to pull 'picture' attribute though. there is much more convenient way, the only thing you need is userid, see example below;
https://graph.facebook.com/user_id/picture?type=large
p.s. type defines the size you want
plz keep in mind that using token with basic permissions, /me/friends will return list of friends only with id+name attributes
I found a solution to this. It's bloody witchcraft, but it works.
When you install the client, open Control Panel > Network Connections.
You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).
Right Click it, click Enable.
The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.
If you're looking to override the behavior of the calendar in general, globally, try editing the Datepicker function (in my example it was line 82),
from
this.autoclose = false;
to
this.autoclose = true;
Worked fine for me, as I wanted to have all my calendar instances behave the same.
IntelliJ IDEA was awsome. Now it is just "better than Eclipse". You can code in IDEA several times faster than in Eclipse in my experience (I moved from being an Eclipse early-adopter to IDEA and haven't looked back) but IDEA has a number of flaws:
I still wouldn't go back though; the code refactorings and intentions in IDEA are just too good.
A major version of Eclipse came out a while back and it took me about an hour of searching on the website to figure out what was actually contained in the release which might persuade me back into the fold. Visit JetBrains to see how to sell an IDE!
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
Just also to draw your attention to this:
https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee
It works great.
I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.
//handle on-demand loading of javascripts
makescript = function(url){
var v = document.createElement('script');
v.src=url;
v.type='text/javascript';
//insertAfter. Get last <script> tag in DOM
d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
d.parentNode.insertBefore( v, d.nextSibling );
}
Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match *Test
rather than *Test*
. That way TestHelper
won't get matched, but FooTest
will.
Repeat
...
Until (JesusChristsReturn) ' Not sure
This question was asked 6 years ago, but it's still worthy to give a simple answer with flexbox layout nowadays.
Just add the following CSS to the father <div>
, it will work.
display: -webkit-flex;
display: flex;
flex-direction: row;
align-items: stretch;
The first two lines declare it will be displayed as flexbox. And flex-direction: row
tells browsers that its children will be display in columns. And align-items: stretch
will meet the requirement that all the children elements will stretch to the same height it one of them become higher.
It is now the first example in the Jersey Client documentation
Example 5.1. POST request with form parameters
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
This is coming from JPA
. In a very simple way:
persist(entity)
should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).
merge(entity)
should be used, to put entity back to persistence context if the entity was detached and was changed.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// Submit Button
String Fname = jTextField1.getText();
String Lname = jTextField2.getText();
String Desig = jTextField3.getText();
String Nic = jTextField4.getText();
String Phone = jTextField5.getText();
String Add = jTextArea1.getText();
String Dob = jTextField6.getText();
// String Gender;
// Image
if (Fname.hashCode() == 0 || Lname.hashCode() == 0 || Desig.hashCode() == 0 || Nic.hashCode() == 0 || Phone.hashCode() == 0 || Add.hashCode() == 0)
{
JOptionPane.showMessageDialog(null, "Some fields are empty!");
}
else
{
JOptionPane.showMessageDialog(null, "OK");
}
}
I am aware that there's already an accepted answer but would like to add my two cents nevertheless:
TLDR: Future and Promise are the two sides of an asynchronous operation: consumer/caller vs. producer/implementor.
As a caller of an asynchronous API method, you will get a Future
as a handle to the computation's result. You can e.g. call get()
on it to wait for the computation to complete and retrieve the result.
Now think of how this API method is actually implemented: The implementor must return a Future
immediately. They are responsible for completing that future as soon as the computation is done (which they will know because it is implementing the dispatch logic ;-)). They will use a Promise
/CompletableFuture
to do just that: Construct and return the CompletableFuture
immediately, and call complete(T result)
once the computation is done.
DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com
You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).
Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
And you're done.
You can also specify a user and a password used to connect:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.
The directoryEntry.Path
Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";
This would match the following AD hierarchy:
Simply write the hierarchy from deepest to highest.
Now you can do plenty of things
For example search a user by account name and get the user's surname:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
PageSize = int.MaxValue,
Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};
searcher.PropertiesToLoad.Add("sn");
var result = searcher.FindOne();
if (result == null) {
return; // Or whatever you need to do in this case
}
string surname;
if (result.Properties.Contains("sn")) {
surname = result.Properties["sn"][0].ToString();
}
For those who looking for Kotlin code:
fun converter(millis: Long): String =
String.format(
"%02d : %02d : %02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millis)
),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millis)
)
)
Sample output: 09 : 10 : 26
You could use UNION
to combine two joins:
SELECT Table1.PhoneNumber1 as PhoneNumber, Table2.SomeOtherField as OtherField
FROM Table1
JOIN Table2
ON Table1.PhoneNumber1 = Table2.PhoneNumber
UNION
SELECT Table1.PhoneNumber2 as PhoneNumber, Table2.SomeOtherField as OtherField
FROM Table1
JOIN Table2
ON Table1.PhoneNumber2 = Table2.PhoneNumber
This worked for me, including recursively into submodules (perhaps that's why your -f didn't work, cause you changed a submodule inside the submodule):
git submodule update -f --recursive
I think an extension of this would get it for you. retrieving-original-row-data-from-jqgrid
Please use the following query to list the tables in your DB.
select name from sys.Tables
In Addition, you can add a where
condition, to skip system generated tables and lists only user created table by adding type ='U'
Ex : select name from sys.Tables where type ='U'
There's a quote on this issue from Daniel Solis' book.
All the predefined types are mapped directly to underlying .NET types. The C# type names (string) are simply aliases for the .NET types (String or System.String), so using the .NET names works fine syntactically, although this is discouraged. Within a C# program, you should use the C# names rather than the .NET names.
There are actually two place where where mac os x serves website by default:
/Library/WebServer/Documents --> http://localhost
~/Sites --> http://localhost/~user/
I did not get it. I had a similar problem but in my nav bar.
What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a
In order to put hover effects on a I positioned a to relative and designed a::before
and a::after
then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a>
they will pop from outside a to fill <a>
.
The problem is that the overflow hidden is not working on <a>
.
What i discovered is if i removed <li>
and simply put <a>
without <ul>
and <li>
then it worked.
What may be the problem?
I'm not an expert in JQuery but I have the same scenario and I able to accomplis like this:
$("#data tr").click(function(){
$(this).addClass("selected").siblings().removeClass("selected");
});
Style:
<style type="text/css">
.selected {
background: red;
}
</style>
You can kill instantly doing it in that way:
private Thread _myThread = new Thread(SomeThreadMethod);
private void SomeThreadMethod()
{
// do whatever you want
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
_myThread.Abort();
}
I always use it and works for me:)
if you try to close the window just after the print() call, it may close the window immediately and print() will don't work. This is what you should not do:
window.open();
...
window.print();
window.close();
This solution will work in Firefox, because on print() call, it waits until printing is done and then it continues processing javascript and close() the window. IE will fail with this because it calls the close() function without waiting for the print() call is done. The popup window will be closed before printing is done.
One way to solve it is by using the "onafterprint" event but I don' recommend it to you becasue these events only works in IE.
The best way is closing the popup window once the print dialog is closed (printing is done or cancelled). At this moment, the popup window will be focussed and you can use the "onfocus" event for closing the popup.
To do this, just insert this javascript embedded code in your popup window:
<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>
Hope this hepls ;-)
Update:
For new chrome browsers it may still close too soon see here. I've implemented this change and it works for all current browsers: 2/29/16
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
int sizeInDP = 16;
int marginInDp = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, sizeInDP, getResources()
.getDisplayMetrics());
Then
layoutParams = myView.getLayoutParams()
layoutParams.setMargins(marginInDp, marginInDp, marginInDp, marginInDp);
myView.setLayoutParams(layoutParams);
Or
LayoutParams layoutParams = new LayoutParams...
layoutParams.setMargins(marginInDp, marginInDp, marginInDp, marginInDp);
myView.setLayoutParams(layoutParams);
Yeah, awendt answer is perfect. I'll just show my working code... I had the context.succeed('Blah'); line right after the reqPost.end(); line. Moving it to where I show below solved everything.
console.log('GW1');
var https = require('https');
exports.handler = function(event, context) {
var body='';
var jsonObject = JSON.stringify(event);
// the post options
var optionspost = {
host: 'the_host',
path: '/the_path',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
var reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function (chunk) {
body += chunk;
});
context.succeed('Blah');
});
reqPost.write(jsonObject);
reqPost.end();
};
You can use the Series.to_list
method.
For example:
import pandas as pd
df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})
print(df['a'].to_list())
Output:
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
To drop duplicates you can do one of the following:
>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]
Sometimes you need to use double brackets, otherwise you get an error like too many arguments
if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
then
fi
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
EDIT: Use an OrderedDictionary.
It's better to use FirstOrDefault()
to retrieve the first value.
Ex:
var firstElement = like.FirstOrDefault();
string firstElementKey = firstElement.Key;
Dictinary<string,string> firstElementValue = firstElement.Value;
Instead of adding variables and strings, you can use the ES6 template strings! Here is an example:
<img className="image" src={`images/${this.props.image}`} />
As for all other JavaScript components inside JSX, use template strings inside of curly braces. To "inject" a variable use a dollar sign followed by curly braces containing the variable you would like to inject. For example:
{`string ${variable} another string`}
In Swift 4:
let string:NSMutableAttributedString = {
let mutableString = NSMutableAttributedString(string: "firstsecondthird")
mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: NSRange(location: 0, length: 5))
mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green , range: NSRange(location: 5, length: 6))
mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: NSRange(location: 11, length: 5))
return mutableString
}()
print(string)
you can try this
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It will remove all the data from the model and reset it.
You can also use the .btn-block
class on the button, so that it expands to the parent's width.
If the parent is a fixed width element the button will expand to take all width. You can apply existing markup to the container to ensure fixed/fluid buttons take up only the required space.
<div class="span2">
<p><button class="btn btn-primary btn-block">Save</button></p>
<p><button class="btn btn-success btn-block">Download</button></p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<div class="span2">_x000D_
<p><button class="btn btn-primary btn-block">Save</button></p>_x000D_
<p><button class="btn btn-success btn-block">Download</button></p>_x000D_
</div>
_x000D_
So as I understand now, SingleOrDefault
will be good if you are querying for data that is guaranteed to be unique i.e. enforced by DB constraints like primary key.
Or is there a better way of querying for the primary key.
Assuming my TableAcc has
AccountNumber - Primary Key, integer
AccountName
AccountOpenedDate
AccountIsActive
etc.
and I want to query for an AccountNumber 987654
, I use
var data = datacontext.TableAcc.FirstOrDefault(obj => obj.AccountNumber == 987654);
ssh-keygen -y
ssh-keygen -y
will prompt you for the passphrase (if there is one).
If you input the correct passphrase, it will show you the associated public key.
If you input the wrong passphrase, it will display load failed
.
If the key has no passphrase, it will not prompt you for a passphrase and will immediately show you the associated public key.
e.g.,
Create a new public/private key pair, with or without a passphrase:
$ ssh-keygen -f /tmp/my_key
...
Now see if you can access the key pair:
$ ssh-keygen -y -f /tmp/my_key
Create a new public/private key pair, with or without a passphrase:
$ ssh-keygen -f /tmp/my_key
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /tmp/my_key.
Your public key has been saved in /tmp/my_key.pub.
The key fingerprint is:
de:24:1b:64:06:43:ca:76:ba:81:e5:f2:59:3b:81:fe [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
| .+ |
| . . o |
| = . + |
| = + + |
| o = o S . |
| + = + * |
| = o o . |
| . . |
| E |
+-----------------+
Attempt to access the key pair by inputting the correct passphrase.
Note that the public key will be shown and the exit status ($?
) will be 0
to indicate success:
$ ssh-keygen -y -f /tmp/my_key
Enter passphrase:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBJhVYDYxXOvcQw0iJTPY64anbwSyzI58hht6xCGJ2gzGUJDIsr1NDQsclka6s0J9TNhUEBBzKvh9nTAYibXwwhIqBwJ6UwWIfA3HY13WS161CUpuKv2A/PrfK0wLFBDBlwP6WjwJNfi4NwxA21GUS/Vcm/SuMwaFid9bM2Ap4wZIahx2fxyJhmHugGUFF9qYI4yRJchaVj7TxEmquCXgVf4RVWnOSs9/MTH8YvH+wHP4WmUzsDI+uaF1SpCyQ1DpazzPWAQPgZv9R8ihOrItLXC1W6TPJkt1CLr/YFpz6vapdola8cRw6g/jTYms00Yxf2hn0/o8ORpQ9qBpcAjJN
$ echo $?
0
Attempt to access the key pair by inputting an incorrect passphrase.
Note that the "load failed" error message will be displayed (message may differ depending on OS) and the exit status ($?
) will be 1
to indicate an error:
$ ssh-keygen -y -f /tmp/my_key
Enter passphrase:
load failed
$ echo $?
1
Attempt to access a key pair that has no passphrase. Note that there is no prompt for the passphrase, the public key will be displayed, and the exit status ($?
) will be 0
to indicate success:
$ ssh-keygen -y -f /tmp/my_key_with_no_passphrase
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLinxx9T4HE6Brw2CvFacvFrYcOSoQUmwL4Cld4enpg8vEiN8DB2ygrhFtKVo0qMAiGWyqz9gXweXhdmAIsVXqhOJIQvD8FqddA/SMgqM++2M7GxgH68N+0V+ih7EUqf8Hb2PIeubhkQJQGzB3FjYkvRLZqE/oC1Q5nL4B1L1zDQYPSnQKneaRNG/NGIaoVwsy6gcCZeqKHywsXBOHLF4F5nf/JKqfS6ojStvzajf0eyQcUMDVhdxTN/hIfEN/HdYbOxHtwDoerv+9f6h2OUxZny1vRNivZxTa+9Qzcet4tkZWibgLmqRyFeTcWh+nOJn7K3puFB2kKoJ10q31Tq19
$ echo $?
0
Note that the order of arguments is important. -y
must come before -f input_keyfile
, else you will get the error Too many arguments.
.
If you're in the middle of a commit (i.e. in your editor already), you can cancel it by deleting all lines above the first #
. That will abort the commit.
So you can delete all lines so that the commit message is empty, then save the file:
You'll then get a message that says Aborting commit due to empty commit message.
.
EDIT:
You can also delete all the lines and the result will be exactly the same.
To delete all lines in vim (if that is your default editor), once you're in the editor, type gg
to go to the first line, then dG
to delete all lines. Finally, write and quit the file with wq
and your commit will be aborted.
There are 2 version of the Java Environments, J2EE and Se. SE is the standard edition, which includes all the basic classes that you would need to write single user applications. While the Enterprise Edition is set up for multi-tiered enterprise applications, or possible distributed applications. If you'd be using app servers, like tomcat or websphere, you'd want to use the J2EE, with the extra classes for n-tier support.
something like that?
'nearest
n = 5
'n = 10
'value
v = 496
'v = 499
'v = 2348
'v = 7343
'mod
m = (v \ n) * n
'diff between mod and the val
i = v-m
if i >= (n/2) then
msgbox m+n
else
msgbox m
end if
By specifying the column as VARCHAR(500)
you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.
If you don't want one, use an unqualified VARCHAR
, or use the TEXT
type.
varchar
and text
are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar
sets a smaller limit manually. All of the following are largely equivalent:
column_name VARCHAR(500)
column_name VARCHAR CHECK (length(column_name) <= 500)
column_name TEXT CHECK (length(column_name) <= 500)
The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.
The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:
regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
and in explicit casts it result in truncation:
regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x
so I think you are using a VARCHAR(500)
column, and you're looking at the wrong table or wrong instance of the database.
Well i have found many answer, But they work fine without text when we require text also with checkbox like in my UI
Here as per my UI requirement i can't not increase TextSize so other option i tried is scaleX and scaleY (Strach the check box) and custom xml selector with .png Images(its also creating problem with different screen size)
But we have another solution for that, that is Vector Drawable
Do it in 3 steps.
Step 1: Copy these three Vector Drawable to your drawable folder
checked.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="16dp"
android:height="16dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M19,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.11,0 2,-0.9 2,-2L21,5c0,-1.1 -0.89,-2 -2,-2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z" />
</vector>
un_checked.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="16dp"
android:height="16dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M19,5v14H5V5h14m0,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2V5c0,-1.1 -0.9,-2 -2,-2z" />
</vector>
(Note if you are workiong with Android Studio, you can also add these Vector Drawable from there, Right click on your drawable folder then New/Vector Asset, then select these drawable from there)
Step 2: Create XML selector for check_box
check_box_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checked" android:state_checked="true" />
<item android:drawable="@drawable/un_checked" />
</selector>
Step 3: Set that drawable into check box
<CheckBox
android:id="@+id/suggectionNeverAskAgainCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:button="@drawable/check_box_selector"
android:textColor="#FF000000"
android:textSize="13dp"
android:text=" Never show this alert again" />
Now its like:
You can change its width and height or viewportHeight and viewportWidth and fillColor also
Hope it will help!
The HTML parser simply doesn't interpret the inlined javascript like this.
You may do this :
<td><input type="checkbox" id="repriseCheckBox" name="repriseCheckBox"/></td>
<script>document.getElementById("repriseCheckBox").disabled=checkStat == 1 ? true : false;</script>
I'm a beginner and wrote a script to ping multiple hosts.To ping multiple host you can use ipaddress module.
import ipaddress
from subprocess import Popen, PIPE
net4 = ipaddress.ip_network('192.168.2.0/24')
for x in net4.hosts():
x = str(x)
hostup = Popen(["ping", "-c1", x], stdout=PIPE)
output = hostup.communicate()[0]
val1 = hostup.returncode
if val1 == 0:
print(x, "is pinging")
else:
print(x, "is not responding")
To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.
As the before-mentioned attachments can and very often are of text/plain or text/html part, this non-bullet-proof sample skips those by checking the content-disposition header:
b = email.message_from_string(a)
body = ""
if b.is_multipart():
for part in b.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# skip any text/plain (txt) attachments
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True) # decode
break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
body = b.get_payload(decode=True)
BTW, walk()
iterates marvelously on mime parts, and get_payload(decode=True)
does the dirty work on decoding base64 etc. for you.
Some background - as I implied, the wonderful world of MIME emails presents a lot of pitfalls of "wrongly" finding the message body. In the simplest case it's in the sole "text/plain" part and get_payload() is very tempting, but we don't live in a simple world - it's often surrounded in multipart/alternative, related, mixed etc. content. Wikipedia describes it tightly - MIME, but considering all these cases below are valid - and common - one has to consider safety nets all around:
Very common - pretty much what you get in normal editor (Gmail,Outlook) sending formatted text with an attachment:
multipart/mixed
|
+- multipart/related
| |
| +- multipart/alternative
| | |
| | +- text/plain
| | +- text/html
| |
| +- image/png
|
+-- application/msexcel
Relatively simple - just alternative representation:
multipart/alternative
|
+- text/plain
+- text/html
For good or bad, this structure is also valid:
multipart/alternative
|
+- text/plain
+- multipart/related
|
+- text/html
+- image/jpeg
Hope this helps a bit.
P.S. My point is don't approach email lightly - it bites when you least expect it :)
EDIT: Below was the preferred solution in 2014. Nowadays you should use @include
, as mentioned in the other answer.
In Laravel views the dot is used as folder separator. So for example I have this code
return View::make('auth.details', array('id' => $id));
which points to app/views/auth/details.blade.php
And to include a view inside a view you do like this:
file: layout.blade.php
<html>
<html stuff>
@yield('content')
</html>
file: hello.blade.php
@extends('layout')
@section('content')
<html stuff>
@stop
Maven
is a build tool. Along with Ant
or Gradle
are Java
s tools for building.
If you are a newbie in Java though just build using your IDE since Maven
has a steep learning curve.
Foto indicator use this:
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.colorWhite));//put your color
You can push the tags like this git push --tags
When you have two or more (in the example below there're three) elements in the string, then you can use comma to separate these items:
date, time, event_name = ev.get_text(separator='@').split("@")
After this line of code, the three variables will have values from three parts of the variable ev
So, if the variable ev contains this string and we apply separator '@':
Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL
Then, after split operation the variable
In Short
android:id="@+id/my_button"
+id Plus sign tells android to add or create a new id in Resources.
while
android:layout_below="@id/my_button"
it just help to refer the already generated id..
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys
where
is probably what you're looking for. So
data=data.where(data=='-', None)
From the panda docs:
where
[returns] an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other).
A good example would be a cache.
For recently accessed objects, you want to keep them in memory, so you hold a strong pointer to them. Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer.
But what if that object is in use and some other code holds a strong pointer to it? If the cache gets rid of its only pointer to the object, it can never find it again. So the cache keeps a weak pointer to objects that it needs to find if they happen to stay in memory.
This is exactly what a weak pointer does -- it allows you to locate an object if it's still around, but doesn't keep it around if nothing else needs it.
Erase an element with index :
vec.erase(vec.begin() + index);
Erase an element with value:
vec.erase(find(vec.begin(),vec.end(),value));
If you're using MacBook.
node.js
in your system and open up the terminal node <filename.js>
example, if filename is script.js
run node script.js
SELECT DISTINCT OBJECT_NAME([id]),[text]
FROM syscomments
WHERE [id] IN (SELECT [id] FROM sysobjects WHERE xtype IN
('TF','FN','V','P') AND status >= 0) AND
([text] LIKE '%text to be search%' )
OBJECT_NAME([id]) --> Object Name (View,Store Procedure,Scalar Function,Table function name)
id (int) = Object identification number
xtype char(2) Object type. Can be one of the following object types:
FN = Scalar function
P = Stored procedure
V = View
TF = Table function
suitable for tcsh .alias file:
alias gisrc 'grep -I -r -i --exclude="*\.svn*" --include="*\."{mm,m,h,cc,c} \!* *'
Took me a while to figure out that the {mm,m,h,cc,c} portion should NOT be inside quotes. ~Keith
As @Roko mentioned you can do this in multiple ways.
1.Using the jQuery first-child selector - SnoopCode
$(document).ready(function(){
$(".alldivs onediv:first-child").css("background-color","yellow");
}
Using jQuery eq Selector - SnoopCode
$( "body" ).find( "onediv" ).eq(1).addClass( "red" );
Using jQuery Id Selector - SnoopCode
$(document).ready(function(){
$("#div1").css("background-color: red;");
});
I created a container and set it the desired height of the view port (depending on the number of charts or chart specific sizes):
.graph-container {
width: 100%;
height: 30vh;
}
To be dynamic to screen sizes I set the container as follows:
*Small media devices specific styles*/
@media screen and (max-width: 800px) {
.graph-container {
display: block;
float: none;
width: 100%;
margin-top: 0px;
margin-right:0px;
margin-left:0px;
height: auto;
}
}
Of course very important (as have been referred to numerous times) set the following option
properties of your chart:
options:{
maintainAspectRatio: false,
responsive: true,
}
While you can make dynamically-created RegExp's (as per the other responses to this question), I'll echo my comment from a similar post: The functional form of String.replace() is extremely useful and in many cases reduces the need for dynamically-created RegExp objects. (which are kind of a pain 'cause you have to express the input to the RegExp constructor as a string rather than use the slashes /[A-Z]+/ regexp literal format)
Workaround....
In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.
For Writing Excel
For Reading Excel
A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.
All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.
A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used in the AsyncTask. The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.
AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.
ie
AsyncTask<Input,Progress,Output>
Just figure out what your Input, Progress and Output are and you will be good to go.
For example
How does
doInbackground()
changes withAsyncTask
parameters?
How
doInBackground()
andonPostExecute()
,onProgressUpdate()
are related?
How can You write this in a code?
DownloadTask extends AsyncTask<String,Integer,String>{
@Override
public void onPreExecute(){
}
@Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
How will you run this Task in Your Activity?
new DownLoadTask().execute("Paradise.mp3");
you just need to divide the Date Time stamp by 1000 like:
var a = 1437203995000;
a = (a)/1000;
Get input1 data to send them to input2 immediately
<div>
<label>Input1</label>
<input type="text" id="input1" value="">
</div>
</br>
<label>Input2</label>
<input type="text" id="input2" value="">
<script type="text/javascript">
$(document).ready(function () {
$("#input1").keyup(function () {
var value = $(this).val();
$("#input2").val(value);
});
});
</script>
Hi if you are having dropdownlist like this
<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">
after giving id to dropdownlist you just need to add jquery code like this
function getHTML()
{
var display=$('#testID option:selected').html();
alert(display);
}
If bitsadmin isn't your cup of tea, you can use this PowerShell command:
Start-BitsTransfer -Source http://www.foo.com/package.zip -Destination C:\somedir\package.zip
Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.
Of course this doesn't help if you have no control over the server.
The only way to override inline style is by using !important
keyword beside the CSS rule. The following is an example of it.
div {
color: blue !important;
/* Adding !important will give this rule more precedence over inline style */
}
_x000D_
<div style="font-size: 18px; color: red;">
Hello, World. How can I change this to blue?
</div>
_x000D_
Important Notes:
Using
!important
is not considered as a good practice. Hence, you should avoid both!important
and inline style.Adding the
!important
keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.It even overrides the inline styles from the markup.
The only way to override is by using another
!important
rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.Must Read - CSS Specificity by MDN
As just formulated by grepsedawk, the answer lies in the -l
option of g++
, calling ld
. If you look at the man page of this command, you can either do:
g++ -l:libmagic.so.1 [...]
g++ -lmagic [...]
, if you have a symlink named libmagic.so in your libs pathI use Visual Studio git plugin, and I have some websites running on IIS I wanted to move. A simple way that worked for me:
Close Visual Studio.
Move the code (including git folder, etc)
Click on the solution file from the new location
This refreshes the mapping to the new location, using the existing local git files that were moved. Once i was back in Visual Studio, my Team Explorer window showed the repos in the new location.
Note that the CDATA
construct is only needed if placing text directly in the XML text file.
That is, you only need to use CDATA
if hand typing or programmatically building the XML text directly.
Any text entered using a DOM processor API or SimpleXML will be automatically escaped to prevent running foul of XML content rules.
Notwithstanding that, there can be times where using CDATA
can reduce the text size that would otherwise be produced with all entities encoded, such as for css in style
tags or javascript in script
tags, where many language constructs use characters in HTML|XML, like <
and >
.
When you make a POST request, you have to encode the data that forms the body of the request in some way.
HTML forms provide three methods of encoding.
application/x-www-form-urlencoded
(the default)multipart/form-data
text/plain
Work was being done on adding application/json
, but that has been abandoned.
(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)
The specifics of the formats don't matter to most developers. The important points are:
text/plain
.When you are writing client-side code:
multipart/form-data
when your form includes any <input type="file">
elementsmultipart/form-data
or application/x-www-form-urlencoded
but application/x-www-form-urlencoded
will be more efficientWhen you are writing server-side code:
Most (such as Perl's CGI->param
or the one exposed by PHP's $_POST
superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.
Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).
If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.
application/x-www-form-urlencoded
is more or less the same as a query string on the end of the URL.
multipart/form-data
is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.
text/plain
is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).
Try this simpler equivalent syntax:
ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";
Run these commands
sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient
Then configure settings.py like
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_db',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': '123456',
}
}
Enjoy mysql connection
For initial array, better use object instead of array, as then you won't be worrying about the indexes and it will be much more clear what is what:
const initialArr = [{
color: "blue",
text: "text1"
}, {
color: "red",
text: "text2"
}];
For actual mapping, use JS Array map instead of for loop - for loop should be used in cases when there's no actual array defined, like displaying something a certain number of times:
onPress = () => {
...
};
renderButtons() {
return initialArr.map((item) => {
return (
<Button
style={{ borderColor: item.color }}
onPress={this.onPress}
>
{item.text}
</Button>
);
});
}
...
render() {
return (
<View style={...}>
{
this.renderButtons()
}
</View>
)
}
I moved the mapping to separate function outside of render method for more readable code. There are many other ways to loop through list of elements in react native, and which way you'll use depends on what do you need to do. Most of these ways are covered in this article about React JSX loops, and although it's using React examples, everything from it can be used in React Native. Please check it out if you're interested in this topic!
Also, not on the topic on the looping, but as you're already using the array syntax for defining the onPress function, there's no need to bind it again. This, again, applies only if the function is defined using this syntax within the component, as the arrow syntax auto binds the function.
Two ways:
<img src="..." border="1" />
or
<img style='border:1px solid #000000' src="..." />
A really simple way to suppress the warning is to add a property in the .csproj
file:
<Project>
<PropertyGroup>
...
<!--disable missing comment warning-->
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
...
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
No, there is not, for starters, it is impossible to have an array with elements sharing the same key
$x =array();
$x['foo'] = 'bar' ;
$x['foo'] = 'baz' ; #replaces 'bar'
Secondarily, if you wish to merely prefix the numbers so that
$x[0] --> $x['foo_0']
That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract" which will prefix numeric keys prior to making them variables.
The very simplest way is this:
function rekey( $input , $prefix ) {
$out = array();
foreach( $input as $i => $v ) {
if ( is_numeric( $i ) ) {
$out[$prefix . $i] = $v;
continue;
}
$out[$i] = $v;
}
return $out;
}
Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.
<section>
<foo_0></foo_0>
<foo_1></foo_1>
<bar></bar>
<foo_2></foo_2>
</section>
Is not good XML.
<section>
<foo></foo>
<foo></foo>
<bar></bar>
<foo></foo>
</section>
Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:
section => {
0 => [ foo , {} ]
1 => [ foo , {} ]
2 => [ bar , {} ]
3 => [ foo , {} ]
}
For what it's worth, the Mock docs talk about datetime.date.today specifically, and it's possible to do this without having to create a dummy class:
https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking
>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
... mock_date.today.return_value = date(2010, 10, 8)
... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
... assert mymodule.date.today() == date(2010, 10, 8)
... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
...
try this code below :
var currentLocation = document.location;
muzLoc = String(currentLocation).substring(0,45);
prodLoc = String(currentLocation).substring(0,48);
techLoc = String(currentLocation).substring(0,47);
If you are sorting strings that are mixed text & numbers, for example filenames of rolling logs then sorting with sort -n
doesn't work as expected:
$ ls |sort -n
output.log.1
output.log.10
output.log.11
output.log.12
output.log.13
output.log.14
output.log.15
output.log.16
output.log.17
output.log.18
output.log.19
output.log.2
output.log.20
output.log.3
output.log.4
output.log.5
output.log.6
output.log.7
output.log.8
output.log.9
In that case option -V
does the trick:
$ ls |sort -V
output.log.1
output.log.2
output.log.3
output.log.4
output.log.5
output.log.6
output.log.7
output.log.8
output.log.9
output.log.10
output.log.11
output.log.12
output.log.13
output.log.14
output.log.15
output.log.16
output.log.17
output.log.18
output.log.19
output.log.20
from man page:
-V, --version-sort natural sort of (version) numbers within text
If you want to know whether if debugging, everywhere in program. Use this.
Declare global variable.
bool isDebug=false;
Create function for checking debug mode
[ConditionalAttribute("DEBUG")]
public static void isDebugging()
{
isDebug = true;
}
In the initialize method call the function
isDebugging();
Now in the entire program. You can check for debugging and do the operations. Hope this Helps!
Use below syntax to create schema class from XSD file.
C:\xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\
Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly.
I was executing the whole command in one line, as it was mentioned as such
$ docker run --name testproject-agent \
-e TP_API_KEY="REPLACE_WITH_YOUR_KEY" \
-e TP_AGENT_ALIAS="My First Agent" \
testproject/agent:latest
But its supposed to be a multiline command, and I copied the command line by line and pressed enter
after every line and bam! it worked.
Sometimes when you copy off of the web, the new-line
character gets omitted, hence my suggestion to try manually introducing the new line.
Another way to think about Return-Path
vs Reply-To
is to compare it to snail mail.
When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path
.
Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To
.
In essence, a Postage Return Address is comparable to SMTP's Return-Path
header and SMTP's Reply-To
header is similar to the replying instructions contained in a letter.
NOBODY above explained/clarified terms to a novice user. They get confused by the terms
.hg/hgrc -- this file is used for Repository, at local/workspace location / in actual repository's .hg folder.
~/.hgrc -- this file is different than the below one. this file resides at ~ or home directory.
myremote.xxxx=..... bb.xxxx=......
This is one of the lines under [auth] section/directive, while using mercurial keyring extension. Make sure the server name you put there, matches with what you use while doing "hg clone" otherwise keyring will say, user not found. bb or myremote in the line below, are "alias name" that you MUST give while doing "hg clone http:/.../../repo1 bb or myremote" otherwise, it wont work or you have to make sure your local repository's .hg/hgrc file contain same alias, ie (what you gave while doing hg clone .. as last parameter).
PS the following links for clear details, sorry for quickly written grammar.
ex: If inside ~/.hgrc (user's home directory in Linux/Unix) or mercurial.ini in Windows at user's home directory, contains, the following line and if you do
`"hg clone http://.../.../reponame myremote"`
, then you'll never be prompted for user credentials more than once per http repo link. In ~/.hgrc under [extensions] a line for "mercurial_keyring = " or "hgext.mercurial_keyring = /path/to/your/mercurial_keyring.py" .. one of these lines should be there.
[auth]
myremote.schemes = http https
myremote.prefix = thsusncdnvm99/hg
myremote.username = c123456
I'm trying to find out how to set the PREFIX property so that user can clone or perform any Hg operations without username/password prompts and without worrying about what he mentioned in the http://..../... for servername while using the Hg repo link. It can be IP, servername or server's FQDN
Maybe try this
Select cust.*
From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null
The Best way and recommended way of comparing date in typescript
is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).
The following class allows you to copy/paste a String to/from the clipboard.
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;
public class SystemClipboard
{
public static void copy(String text)
{
Clipboard clipboard = getSystemClipboard();
clipboard.setContents(new StringSelection(text), null);
}
public static void paste() throws AWTException
{
Robot robot = new Robot();
int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
robot.keyPress(controlKey);
robot.keyPress(VK_V);
robot.keyRelease(controlKey);
robot.keyRelease(VK_V);
}
public static String get() throws Exception
{
Clipboard systemClipboard = getSystemClipboard();
DataFlavor dataFlavor = DataFlavor.stringFlavor;
if (systemClipboard.isDataFlavorAvailable(dataFlavor))
{
Object text = systemClipboard.getData(dataFlavor);
return (String) text;
}
return null;
}
private static Clipboard getSystemClipboard()
{
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
return defaultToolkit.getSystemClipboard();
}
}
Here's a quick and dirty ctypes tutorial.
First, write your C library. Here's a simple Hello world example:
#include <stdio.h>
void myprint(void);
void myprint()
{
printf("hello world\n");
}
Now compile it as a shared library (mac fix found here):
$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c
# or... for Mac OS X
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c
Then, write a wrapper using ctypes:
import ctypes
testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()
Now execute it:
$ python testlibwrapper.py
And you should see the output
Hello world
$
If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib
or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL()
.
This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.
PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6')
. If you're on another OS, things might change a little bit (or quite a lot).
Very similar to this question, and I would suggest the same formula in column D, albeit a few changes to the ranges:
=IFERROR(VLOOKUP(C1, A:B, 2, 0), "")
If you wanted to use match, you'd have to use INDEX
as well, like so:
=IFERROR(INDEX(B:B, MATCH(C1, A:A, 0)), "")
but this is really lengthy to me and you need to know how to properly use two functions (or three, if you don't know how IFERROR
works)!
Note: =IFERROR()
can be a substitute of =IF()
and =ISERROR()
in some cases :)
On RHEL Linux, I had trouble getting my message in the body of the email instead of as an attachment . Using od -cx, I found that the body of my email contained several /r. I used a perl script to strip the /r, and the message was correctly inserted into the body of the email.
mailx -s "subject text" [email protected] < 'body.txt'
The text file body.txt contained the char \r, so I used perl to strip \r.
cat body.txt | perl success.pl > body2.txt
mailx -s "subject text" [email protected] < 'body2.txt'
This is success.pl
while (<STDIN>) {
my $currLine = $_;
s?\r??g;
print
}
;
As @Devart says, the total length of your index is too long.
The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.
The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.
You can declare a prefix length per column as you define the index. For example:
...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...
But what's the best prefix length for a given column? Here's a method to find out:
SELECT
ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;
It tells you the proportion of rows that have no more than a given string length in the menu_link
column. You might see output like this:
+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
| 21.78 | 80.20 | 100.00 | 100.00 |
+---------------+---------------+---------------+----------------+
This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.
PS: The INT(1)
and INT(32)
data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT
is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL
option.
bad_words = ['doc:', 'strickland:','\n']
with open('linetest.txt') as oldfile, open('linetestnew.txt', 'w') as newfile:
for line in oldfile:
if not any(bad_word in line for bad_word in bad_words):
newfile.write(line)
The \n
is a Unicode escape sequence for a newline.