This should help you..:
import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
find(Recipe);
}
public void find(String Name){
String newRecipe= Name+".txt";
try{
FileReader fr= new FileReader(newRecipe);
BufferedReader br= new BufferedReader(fr);
String str;
while ((str=br.readLine()) != null){
out.println(str + "\n");
}
br.close();
}catch (IOException e){
out.println("File Not Found!");
}
}
}
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent()
and fixedEncodeURI()
. Long-story...
You should not be using encodeURIComponent()
or encodeURI()
. You should use fixedEncodeURIComponent()
and fixedEncodeURI()
, according to the MDN Documentation.
Regarding encodeURI()
...
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
Regarding encodeURIComponent()
...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
So, what is the difference? fixedEncodeURI()
and fixedEncodeURIComponent()
convert the same set of values, but fixedEncodeURIComponent()
also converts this set: +@?=:*#;,$&
. This set is used in GET
parameters (&
, +
, etc.), anchor tags (#
), wildcard tags (*
), email/username parts (@
), etc..
For example -- If you use encodeURI()
, [email protected]/?email=me@home
will not properly send the second @
to the server, except for your browser handling the compatibility (as Chrome naturally does often).
To be clear when you us the drag indicator it will only copy the cell values down the column whilst there is a value in the adjacent cell in a given row. As soon as the drag operation sees an adjacent cell that is blank it will stop copying the formula down.
.e.g
1,a,b
2,a
3,
4,a
If the above is a spreadsheet then using the double click drag indicator on the 'b' cell will fill row 2 but not row three or four.
Suppose we have a df_data data frame as below
> df_data
ID MONTH-YEAR VALUE
1 110 JAN.2012 1000
2 111 JAN.2012 2000
3 121 FEB.2012 3000
4 131 FEB.2012 4000
5 141 MAR.2012 5000
To count number of rows in df_data grouped by MONTH-YEAR column, you can use:
> summary(df_data$`MONTH-YEAR`)
FEB.2012 JAN.2012 MAR.2012
2 2 1
summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)
Declare in your Model with
[DataType(DataType.MultilineText)]
public string urString { get; set; }
Then in .cshtml can make use of editor as below. you can make use of @cols and @rows for TextArea size
@Html.EditorFor(model => model.urString, new { htmlAttributes = new { @class = "",@cols = 35, @rows = 3 } })
Thanks !
This is what helped me to understand the difference, thanks to a blog post by Pascal Precht.
A service is a method on a module that takes a name and a function that defines the service. You can inject and use that particular service in other components, like controllers, directives and filters. A factory is a method on a module and it also takes a name and a function, that defines the factory. We can also inject and use the it same way we did with the service.
Objects created with new use the value of the prototype property of their constructor function as their prototype, so I found the Angular code that calls Object.create(), that I believe is the service constructor function when it gets instantiated. However, a factory function is really just a function that gets called, which is why we have to return an object literal for the factory.
Here is the angular 1.5 code I found for factory:
var needsRecurse = false;
var destination = copyType(source);
if (destination === undefined) {
destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
needsRecurse = true;
}
Angular source code snippet for the factory() function:
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
It takes the name and the factory function that is passed and returns a provider with the same name, that has a $get method which is our factory function. Whenever you ask the injector for a specific dependency, it basically asks the corresponding provider for an instance of that service, by calling the $get() method. That’s why $get() is required, when creating providers.
Here is the angular 1.5 code for service.
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It turns out that when we call service(), it actually calls factory()! However, it doesn’t just pass our service constructor function to the factory as is. It also passes a function that asks the injector to instantiate an object by the given constructor.
In other words, if we inject MyService somewhere, what happens in the code is:
MyServiceProvider.$get(); // return the instance of the service
To restate it again, a service calls a factory, which is a $get() method on the corresponding provider. Moreover, $injector.instantiate() is the method that ultimately calls Object.create() with the constructor function. That’s why we use "this" in services.
For ES5 it doesn't matter which we use: service() or factory(), it’s always a factory that is called which creates a provider for our service.
You can do the exact same thing with services as well though. A service is a constructor function, however, that doesn’t prevent us from returning object literals. So we can take our service code and write it in a way that it basically does the exact same thing as our factory or in other words, you can write a service as a factory to return an object.
Why do most people recommend to use factories over services? This is the best answer I've seen which comes from Pawel Kozlowski's book: Mastering Web Application Development with AngularJS.
The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service."
use encodeURIComponent function to fix url, it works on Browser and node.js
res.redirect("/signin?email="+encodeURIComponent("[email protected]"));
> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'
The simplest solution would be (using 'upstream
' as the remote name referencing the original repo forked):
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master
git push origin master --force
(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")
Be aware that you can lose changes done on the master
branch (both locally, because of the reset --hard
, and on the remote side, because of the push --force
).
An alternative would be, if you want to preserve your commits on master
, to replay those commits on top of the current upstream/master
.
Replace the reset part by a git rebase upstream/master
. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"
A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".
See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream
" is.
Note: recent GitHub repos do protect the master
branch against push --force
.
So you will have to un-protect master
first (see picture below), and then re-protect it after force-pushing).
Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.
Nothing as useful as this: Common Data Structure Operations:
To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.
\fontsize{10}{12}\selectfont This is the text you need to be in 10px
More info: https://tug.org/TUGboat/tb33-3/tb105thurnherr.pdf
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
To ignore:
git update-index --assume-unchanged <path/to/file>
To undo ignore:
git update-index --no-assume-unchanged <path/to/file>
Install the gd library also.
check this link http://www.php.net/manual/en/mbstring.installation.php
Edit: As of 0.1.8 this is now supported in the IDE. Please follow the instructions in there, instead of using the instructions below.
Following the Android Gradle Plugin User Guide I was able to get tests working on the command line by performing the following steps on a newly created project (I used the default 'com.example.myapplication' package):
This ran my tests and placed the test results in MyApplicationProject/MyApplication/build/reports/instrumentTests/connected. I'm new to testing Android apps, but it seem to work fine.
From within the IDE, it's possible to try and run the same test class. You'll need to
However this fails (the classpath used when running the tests is missing the test output directory). However, I'm not sure that this would work regardless as it's my understanding that an Android specific test runner is required.
Elizabeth Castro has an interesting article on this problem: Bye Bye Embed. Worth a read on how she attacked this problem, as well as handling QuickTime content.
Crossframe-Scripting is not possible when the two frames have different domains -> Security.
See this: http://javascript.about.com/od/reference/a/frame3.htm
Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.
I learned how to do these sort of things reading "PRO HTML and CSS Design Patterns". The display:block
is the default display value for the div
, but I like to make it explicit. The container has to be the right type; position
attribute is fixed
, relative
, or absolute
.
.stretchedToMargin {_x000D_
display: block;_x000D_
position:absolute;_x000D_
height:auto;_x000D_
bottom:0;_x000D_
top:0;_x000D_
left:0;_x000D_
right:0;_x000D_
margin-top:20px;_x000D_
margin-bottom:20px;_x000D_
margin-right:80px;_x000D_
margin-left:80px;_x000D_
background-color: green;_x000D_
}
_x000D_
<div class="stretchedToMargin">_x000D_
Hello, world_x000D_
</div>
_x000D_
[Joke mode on]
You can fix this by adding this:
https://github.com/donavon/undefined-is-a-function
import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.
[joke mode off]
^
is not the operator you want. You are looking for the pow
function of java.lang.Math
.
You can use Math.pow(value, power)
.
Example:
Math.pow(23, 5); // 23 to the fifth power
Add <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version> in property tag
problem resolve
https://medium.com/@saannjaay/unknown-error-in-pom-xml-66fb2414991b
you can use CURRENT_TIMESTAMP, mysql function
Add overflow: auto;
to the style and the two finger scroll should work.
We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:
https://gitlab.example.com/<group>/<project>/commit/<commit hash>
We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.
to check out your PATH
variable, act as follow:
Once there, scroll to get the Path
row, you'll get a long string of paths (e.g. C:\windows\bin;C:\program files\git
, etc)
Find the line or lines where git
is referenced. Then, make sure this path point to your Git 1.8.x installation. If not, delete it and add the real path to the newest Git version. At the end, you should only have one path in the string linking to Git.
How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?
In L2S you can add
public partial class NWDataContext
{
partial void InsertCategory(Category instance)
{
if(Instance.Date == null)
Instance.Data = DateTime.Now;
ExecuteDynamicInsert(instance);
}
}
EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.
Guessing from your directory name, you are trying to access the repository on the local filesystem. You still need to use URL syntax to access it:
svn export file:///e:/repositories/process/test.txt c:\test.txt
Thanks.I changed heap space from 2000MB to 1024MB and it worked...
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
You should specify formGroupName
for nested controls
<div class="panel panel-default" formGroupName="address"> <== add this
<div class="panel-heading">Contact Info</div>
Just remove the slash after Data
and prepend the root:
<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
From terminal, find all eclipse directories with
sudo find / -iname "Eclipse"
Delete those directories with rm
command.
with this code, the id will not appear on the link
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx
I implemented this function almost exactly as written, but what happened is I got this error:
2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080
This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!
private Socket ConnectSocket(string server, int port)
{
Socket s = null;
try
{
// Get host related information.
IPAddress[] ips;
ips = Dns.GetHostAddresses(server);
Socket tempSocket = null;
IPEndPoint ipe = null;
ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
s.SendTimeout = Coordinate.HL7SendTimeout;
s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
}
else
{
return null;
}
return s;
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
if (g_NoOutputForThreading == false)
rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
return null;
}
}
You have to implement KeyListener
,take a look here:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
More details on how to use it: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Use mouseup and keyup
$(":input").bind('keyup mouseup', function () {
alert("changed");
});
DATEPART function doesn't work on MySQL 5.6, instead use MONTH('2018-01-01')
As discussed in the comments, this can be achieved by converting the entry into Date
format and extracting the year, for instance like this:
format(as.Date(df1$Date, format="%d/%m/%Y"),"%Y")
Potentially for a different question, but I'm providing my version of @Alvero's answer (using unidecode). I want to do a "regular" strip on my strings, i.e. the beginning and end of my string for whitespace characters, and then replace only other whitespace characters with a "regular" space, i.e.
"Ceñía?mañana????"
to
"Ceñía mañana"
,
def safely_stripped(s: str):
return ' '.join(
stripped for stripped in
(bit.strip() for bit in
''.join((c if unidecode(c) else ' ') for c in s).strip().split())
if stripped)
We first replace all non-unicode spaces with a regular space (and join it back again),
''.join((c if unidecode(c) else ' ') for c in s)
And then we split that again, with python's normal split, and strip each "bit",
(bit.strip() for bit in s.split())
And lastly join those back again, but only if the string passes an if
test,
' '.join(stripped for stripped in s if stripped)
And with that, safely_stripped('????Ceñía?mañana????')
correctly returns 'Ceñía mañana'
.
We had this case where an .html file was seen as binary whenever we tried to make changes in it. Very uncool to not see diffs. To be honest, I didn't checked all the solutions here but what worked for us was the following:
git deletion
. Git says Deleted file with mode 100644 (Regular) Binary file differs
New file with mode 100644 (Regular) 1 chunk, 135 insertions, 0 deletions
The file
is now added as a regular text fileFrom now on, any changes I made in the file is seen as a regular text diff. You could also squash these commits (1, 2, and 3 being the actual change you make) but I prefer to be able to see in the future what I did. Squashing 1 & 2 will show a binary change.
The issue caused by the docker container which exits as soon as the "start" process finishes. i added a command that runs forever and it worked. This issue mentioned here
For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
For me I just noticed that it was my .h archive with a '{'. Maye that can help someone =)
class Test
{
Dictionary<int, string> entities;
public string GetEntity(int code)
{
// java's get method returns null when the key has no mapping
// so we'll do the same
string val;
if (entities.TryGetValue(code, out val))
return val;
else
return null;
}
}
// For current url
echo base_url(uri_string());
Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build
without errors.
Both gradle build
and gradle -PmainClass=foo runApp
work with this:
task runApp(type:JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}
where you set your default main class.
The new Selenium IDE (released in 2019) has a much broader API and new documentation.
I believe this is the command you'll want to try:
webdriver choose ok on visible confirmation
Described at:
There are other alert-related API calls; just search that page for alert
public MainPage()
{
this.InitializeComponent();
...
...
...
//Make Start result text copiable
TextBlockStatusStart.IsTextSelectionEnabled = true;
}
[https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android][1]
For people trying out this example and facing issues with latest NDK. Can follow this solution. In build.gradle change this
classpath 'com.android.tools.build:gradle:3.0.1'
To
classpath 'com.android.tools.build:gradle:3.1.2'
The reason is mips are deprecated in the latest ndk versions, Gradle version 3.1.2 will not have a compulsion for mips. It assumes the presence for these missing folders.
Here is a solution to prevent session shearing between browser tabs for a java application. This will work for IE (JSP/Servlet)
1)first page JS
BODY onload="javascript:initPageLoad()"
function initPageLoad() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText;
top.document.title=serverResponse;
}
};
xmlhttp.open("GET", 'data.do', true);
xmlhttp.send();
}
2)common JS for all pages
window.onunload = function() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var serverResponse = xmlhttp.responseText;
}
};
xmlhttp.open("GET", 'data.do?reset=true', true);
xmlhttp.send();
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
init();
clearInterval(readyStateCheckInterval);
}}, 10);
function init(){
if(document.title==""){
window.onunload=function() {};
window.open('', '_self', ''); window.close();
}
}
3)web.xml - servlet mapping
<servlet-mapping>
<servlet-name>myAction</servlet-name>
<url-pattern>/data.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>myAction</servlet-name>
<servlet-class>xx.xxx.MyAction</servlet-class>
</servlet>
4)servlet code
public class MyAction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Integer sessionCount = (Integer) request.getSession().getAttribute(
"sessionCount");
PrintWriter out = response.getWriter();
Boolean reset = Boolean.valueOf(request.getParameter("reset"));
if (reset)
sessionCount = new Integer(0);
else {
if (sessionCount == null || sessionCount == 0) {
out.println("hello Title");
sessionCount = new Integer(0);
}
sessionCount++;
}
request.getSession().setAttribute("sessionCount", sessionCount);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "private, no-store, no-cache, must- revalidate");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
}
First of all, checked
can have a value of checked
, or an empty string.
$("input:checkbox").uniform();
$('#check1').live('click', function() {
$('#check2').attr('checked', 'checked').uniform();
});
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
I wrote extension method
public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
var s = new StringBuilder();
for (var i = 0; i < matrix.GetLength(0); i++)
{
for (var j = 0; j < matrix.GetLength(1); j++)
{
s.Append(matrix[i, j]).Append(delimiter);
}
s.AppendLine();
}
return s.ToString();
}
To use just call the method
results.ToMatrixString();
Original Answer
Windows Grep does this really well.
Edit: Windows Grep is no longer being maintained or made available by the developer. An alternate download link is here: Windows Grep - alternate
Current Answer
Visual Studio Code has excellent search and replace capabilities across files. It is extremely fast, supports regex and live preview before replacement.
list(your_iterator)
How to fade borders with CSS:
<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>
Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.
Source: Gradient Borders
Your example works for conditioned classes (the class name will show if the expressionDataX
is true):
<div ng-class="{class1: expressionData1, class2: expressionData2}"></div>
You can also add multiple classes, supplied by the user of the element:
<div ng-class="[class1, class2]"></div>
Usage:
<div class="foo bar" class1="foo" class2="bar"></div>
I would prefer to see the use of a css class here. It avoids having hard to read colors / hex codes in javascript.
document.body.className = className;
It's simpler if you modify your HTML a little bit:
<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />
<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />
then it's relatively simple
$(document).ready(function() {
$('#name').change(function() {
$('#firstname').val($('#name').val());
});
});
Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:
https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/
This is a big gray area in cookie SOP (Same Origin Policy).
Theoretically, you can specify port number in the domain and the cookie will not be shared. In practice, this doesn't work with several browsers and you will run into other issues. So this is only feasible if your sites are not for general public and you can control what browsers to use.
The better approach is to get 2 domain names for the same IP and not relying on port numbers for cookies.
You are running Composer with SSL/TLS protection disabled.
composer config --global disable-tls true
composer config --global disable-tls false
In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.
Thus you can write
for elm = list
%# do something with the element
end
Note that Matlab iterates through the columns of list
, so if list
is a nx1 vector, you may want to transpose it.
I recently run into the same problem. I solved it by implementing my own ImageView class.
Here is my Kotlin implementation:
class MyImageView(context: Context): ImageView(context) {
private var currentDrawableId: Int? = null
override fun setImageResource(resId: Int) {
super.setImageResource(resId)
currentDrawableId = resId
}
fun getDrawableId() {
return currentDrawableId
}
fun compareCurrentDrawable(toDrawableId: Int?): Boolean {
if (toDrawableId == null || currentDrawableId != toDrawableId) {
return false
}
return true
}
}
Instead of passing the properties as an argument, you may use a .properties for storing them.
If the string is already in list format, you can use the JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.
After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.
Best of luck on finding a solution!
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
If none of this did not help, then try to swap ^ in "^version" to ~ "~version".
I had a table change and it created another entity with a number 1 at the end (such as MyEntity1
and a MyEntity
) as confirmed by the edmx model browser. Something about the two entities together confused the processing.
Removal of the table and re-adding it fixed it.
Note that if TFS is hooked up, then do a check-in of the edmx in after the delete. Then and only then get the latest and re-add it in a definite two step process. Otherwise TFS gets confused with the delete and re-add of same named entity(ies) which seems to cause problems.
in /etc/my.cnf
:
[mysqld]
...
performance_schema = 0
table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000
query_cache_size = 0
query_cache_limit = 0
...
Good work on server with 256MB Memory.
Note, that starting from PostgreSQL 8.4 you can get all information about sequences used in the database via:
SELECT * FROM information_schema.sequences;
Since I'm using a higher version of PostgreSQL (9.1), and was searching for same answer high and low, I added this answer for posterity's sake and for future searchers.
I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command
grep -r --color foo /opt
with no issue. With Cygwin /
represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.
Uninstall what Git you have and install the Cygwin git package, save yourself the headache.
I'd suggest following a few debugging steps.
First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.
If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.
If your data is output onto the page, then look at what's going wrong in your HTML formatting.
However, if nothing is output from $row
, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]
Changing your query slightly to
$sql = mysql_query("SELECT username FROM users") or die(mysql_error());
may help to highlight any errors: php manual
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
For a variable number of arguments like this the only way I'm aware of is to either generate the SQL explicitly or do something that involves populating a temporary table with the items you want and joining against the temp table.
Use the preprocessor #
operator:
#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!
Here's how I installed in Ubuntu-based image:
https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8
RUN docker-php-ext-install mysql mysqli pdo pdo_mysql
Building and running your application is just a 2 step process (considering you are in the current directory of the app):
$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp
I was dealing with DateTimeOffset
and unfortunately the "o" prints out "+0000" not "Z".
So I ended up with:
dateTimeOffset.UtcDateTime.ToString("o")
I solved it this way: download the zipped package from here and follow this set of instructions:
unzip /path/to/downloads/folder/mysql-connector-python-VER.zip
In case u got a .gz
u can use ->
tar xzf mysql-connector-python-VER.tar.gz
And then:
cd mysql-connector-python-VER # move into the directory
sudo python3 setup.py install # NOTICE I USED PYTHON3 INSTEAD OF PYTHON
You can read about it here
As described here, you can also attempt the command
npm cache clean
That fixed it for me, after the other steps had not fully yielded results (other than updating everything).
You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.
If boolean() is not available (the tool I'm using does not) one way to achieve it is:
//SELECT[@id='xpto']/OPTION[not(not(@selected))]
In this case, within the /OPTION, one of the options is the selected one. The "selected" does not have a value... it just exists, while the other OPTION do not have "selected". This achieves the objective.
The method setAlpha(int)
from the type ImageView is deprecated.
Instead of
image.setImageAlpha(127);
//value: [0-255]. Where 0 is fully transparent and 255 is fully opaque.
PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:
I opened the popup directly on the users click, directed the url to about:blank
and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made
var myWindow = window.open("about:blank",'name','height=500,width=550');
Then, when my request is successful, I open my callback url in the window
function showWindow(win, url) {
win.open(url,'name','height=500,width=550');
}
Anthony
try the below one. it will give ur expected output
select c.name as Fields from
tempdb.sys.columns c
inner join tempdb.sys.tables t
ON c.object_id = t.object_id
where t.name like '#MyTempTable%'
instead of id use title to identify your element and write the code as below.
$(document).ready(()=>{
$("input[title='MyObject']").change(()=>{
console.log("Field has been changed...")
})
});
You could also have a look at testing using Groovy. In Groovy you can easily mock Java interfaces using the 'as' operator:
def request = [isUserInRole: { roleName -> roleName == "testRole"}] as HttpServletRequest
Apart from this basic functionality Groovy offers a lot more on the mocking front, including the powerful MockFor
and StubFor
classes.
Please take care that the epoch time is in second and Date object accepts Long value which is in milliseconds. Hence you would have to multiply epoch value with 1000 to use it as long value . Like below :-
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
Long dateLong=Long.parseLong(sdf.format(epoch*1000));
https://developer.mozilla.org/en/CSS/Media_queries#-moz-device-pixel-ratio
-moz-device-pixel-ratio
Gives the number of device pixels per CSS pixel.
this is almost self-explaining. the number describes the ratio of how much "real" pixels (physical pixerls of the screen) are used to display one "virtual" pixel (size set in CSS).
I have found Adobe Dreamweaver to be quite good at that. However, it's not free.
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
Mutable means you will save the same reference to variable and change its contents but immutable you can not change contents but you will declare new reference contains the new and the old value of the variable
Ex Immutable -> String
String x = "value0ne";// adresse one
x += "valueTwo"; //an other adresse {adresse two}
adresse on the heap memory change.
Mutable -> StringBuffer - StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("valueOne"); // adresse One
sb.append("valueTwo"); // adresse One
sb still in the same adresse i hope this comment helps
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList
instead of array:
List<Car> garage = new ArrayList<Car>();
garage.add(redCar);
If your modal div is dynamically added then use( For bootstrap 3 and 4)
$(document).on('hide.bs.modal','#modal-id', function () {
alert('');
//Do stuff here
});
This will work for non-dynamic content also.
This one-liner tells where the shell script is, does not matter if you ran it or if you sourced it. Also, it resolves any symbolic links involved, if that is the case:
dir=$(dirname $(test -L "$BASH_SOURCE" && readlink -f "$BASH_SOURCE" || echo "$BASH_SOURCE"))
By the way, I suppose you are using /bin/bash.
Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.
TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.
See Do I need to heartbeat to keep a TCP connection open? for more discussion.
window.document.removeEventListener("keydown", getEventListeners(window.document.keydown[0].listener));
May be several anonymous functions, keydown1
Warning: only works in Chrome Dev Tools
& cannot be used in code: link
If you need to store a member function without the class instance, you can do something like this:
class MyClass
{
public:
void MemberFunc(int value)
{
//do something
}
};
// Store member function binding
auto callable = std::mem_fn(&MyClass::MemberFunc);
// Call with late supplied 'this'
MyClass myInst;
callable(&myInst, 123);
What would the storage type look like without auto? Something like this:
std::_Mem_fn_wrap<void,void (__cdecl TestA::*)(int),TestA,int> callable
You can also pass this function storage to a standard function binding
std::function<void(int)> binding = std::bind(callable, &testA, std::placeholders::_1);
binding(123); // Call
Past and future notes: An older interface std::mem_func existed, but has since been deprecated. A proposal exists, post C++17, to make pointer to member functions callable. This would be most welcome.
you can also mark the application as private if you don’t plan to put it in an actual repository.
{
"name": "my-application",
"version": "0.0.1",
"private": true
}
This actually works for me:
Per the README.SSO that comes with the jtdsd distribution:
In order for Single Sign On to work, jTDS must be able to load the native SPPI library ntlmauth.dll
. Place this DLL anywhere in the system path (defined by the PATH
system variable) and you're all set.
I placed it in my jre/bin folder
I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name.
jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print
can be get using the str()
function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you '2008-11-22 19:53:42'
.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr()
function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'
.
What happened is that when you have printed the date using print
, it used str()
so you could see a nice date string. But when you have printed mylist
, you have printed a list of objects and Python tried to represent the set of data, using repr()
.
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str()
. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date)
.
One last thing. When you tried to print the dates, you printed mylist
. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist :
print str(date)
Note that in that specific case, you can even omit str()
because print will use it for you. But it should not become a habit :-)
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime()
method.
strftime()
expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
All the letter after a "%"
represent a format for something:
%d
is the day number (2 digits, prefixed with leading zero's if necessary)%m
is the month number (2 digits, prefixed with leading zero's if necessary)%b
is the month abbreviation (3 letters)%B
is the month name in full (letters)%y
is the year number abbreviated (last 2 digits)%Y
is the year number full (4 digits)etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
You can use modern Java to solve this problem. Please use the code below:
static int findIndexOf(int V, int[] arr) {
return IntStream.range(0, arr.length)
.filter(i->arr[i]==V)
.findFirst()
.getAsInt();
}
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
Obviously you can use maxLength in xml or InputFilter.LengthFilter as answered above. But for me in some cases, it was not enough. I created a class for more flexible settings of EditText: https://github.com/devapro/NumberWatcher It is implementation only for numbers input, but you can change it for any of the types.
AutoFilterMode will be True if engaged, regardless of whether there is actually a filter applied to a specific column or not. When this happens, ActiveSheet.ShowAllData
will still run, throwing an error (because there is no actual filtering).
I had the same issue and got it working with
If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
This seems to prevent ShowAllData from running when there is no actual filter applied but with AutoFilterMode turned on.
The second catch Or ActiveSheet.FilterMode
should catch advanced filters
You can use the library on Mozilla website here
You'll be able to set and get cookies like this
docCookies.setItem(name, value);
docCookies.getItem(name);
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
The other one doesn't work. According to the docs this is the way you should do it.
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
test: function () {
return 'test variable';
}
}
});
};
var ModalInstanceCtrl = function ($scope, $modalInstance, test) {
$scope.test = test;
};
Have you tried the power button :) ... it really worked for me. Actually emulator saves the device state before closing so at the last run if you switched off the device & closed the emulator then in the next run it will load previous state & display switched off phone aka blank screen. Although there might be many other causes of this issue.
The javascript has
var canvasW = 640;
var canvasH = 480;
in it. Try changing those as well as the css for the canvas.
Or better yet, have the initialize function determine the size of the canvas from the css!
in response to your edits, change your init function:
function init()
{
canvas = document.getElementById("mainCanvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
canvasW = canvas.width;
canvasH = canvas.height;
if( canvas.getContext )
{
setup();
setInterval( run , 33 );
}
}
Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.
html, body {
overflow: hidden;
}
Edit: document.width
and document.height
are obsolete. Replace with document.body.clientWidth
and document.body.clientHeight
this is my sample you can use:
public static string GetFileNameValidChar(string fileName)
{
foreach (var item in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(item.ToString(), "");
}
return fileName;
}
public static string GetFileNameFromUrl(string url)
{
string fileName = "";
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
}
string ext = "";
if (!string.IsNullOrEmpty(fileName))
{
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
return GetFileNameValidChar(fileName + ext);
}
fileName = Path.GetFileName(url);
if (string.IsNullOrEmpty(fileName))
{
fileName = "noName";
}
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
fileName = fileName + ext;
if (!fileName.StartsWith("?"))
fileName = fileName.Split('?').FirstOrDefault();
fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
return GetFileNameValidChar(fileName);
}
Usage:
var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");
A percentage in the value of the font-size
property is relative to the parent element’s font size. CSS 2.1 says this obscurely and confusingly (referring to “inherited font size”), but CSS3 Text says it very clearly.
The parent of the body
element is the root element, i.e. the html
element. Unless set in a style sheet, the font size of the root element is implementation-dependent. It typically depends on user settings.
Setting font-size: 100%
is pointless in many cases, as an element inherits its parent’s font size (leading to the same result), if no style sheet sets its own font size. However, it can be useful to override settings in other style sheets (including browser default style sheets).
For example, an input
element typically has a setting in browser style sheet, making its default font size smaller than that of copy text. If you wish to make the font size the same, you can set
input { font-size: 100% }
For the body
element, the logically redundant setting font-size: 100%
is used fairly often, as it is believed to help against some browser bugs (in browsers that probably have lost their significance now).
I suspect you are having a problem with factors. For example,
> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8
Some comments:
as.numeric
to do with these values?read.csv
, try using the argument stringsAsFactors=FALSE
sep="/t
and not sep="\t"
head(pitchman)
to check the first fews rows of your datapichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
since I don't have access to the data set.Your hosts file does not include a valid FQDN, nor is localhost
an FQDN. An FQDN must include a hostname part, as well as a domain name part. For example, the following is a valid FQDN:
host.server4-245.com
Choose an FQDN and include it both in your /etc/hosts
file on both the IPv4 and IPv6 addresses you are using (in your case, localhost
or 127.0.0.1
), and change your ServerName
in your httpd configuration to match.
/etc/hosts:
127.0.0.1 localhost.localdomain localhost host.server4-245.com
::1 localhost.localdomain localhost host.server4-245.com
httpd.conf:
ServerName host.server4-245.com
You can use this: document.getElementById('h1_id').innerHTML = 'the new text';
Yes. You need to close the resultset, the statement and the connection. If the connection has come from a pool, closing it actually sends it back to the pool for reuse.
You typically have to do this in a finally{}
block, such that if an exception is thrown, you still get the chance to close this.
Many frameworks will look after this resource allocation/deallocation issue for you. e.g. Spring's JdbcTemplate. Apache DbUtils has methods to look after closing the resultset/statement/connection whether null or not (and catching exceptions upon closing), which may also help.
try this :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript"><!--
function getVal(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
alert(targ.innerHTML);
}
onload = function() {
var t = document.getElementById("main").getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
</script>
<body>
<table id="main"><tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr><tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr><tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr></table>
</body>
</html>
Prerequisite:
Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control
Aria does not change anything visually. (Aria is scared of designers too).
aria-label
aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users
How To Use:
<input type="edit" aria-label="search" placeholder="search">
There is no visual change in application. But screen readers can understand the purpose of control
aria-labelledby
Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually
Approach 1:
<span id="sd">Search</span>
<input type="text" aria-labelledby="sd">
Approach 2:
aria-labelledby can also be used to combine two labels for screen reader users
<span id="de">Billing Address</span>
<span id="sd">First Name</span>
<input type="text" aria-labelledby="de sd">
The approximate conversions are:
This doesn't fully correct for the Earth's polar flattening - for that you'd probably want a more complicated formula using the WGS84 reference ellipsoid (the model used for GPS). But the error is probably negligible for your purposes.
Source: http://en.wikipedia.org/wiki/Latitude
Caution: Be aware that latlong coordinates are expressed in degrees, while the cos
function in most (all?) languages typically accepts radians, therefore a degree to radians conversion is needed.
One more way:
git diff stash@{N}^! -- path/to/file1 path/to/file2 | git apply -R
You can just simply use Flexbox like this:
#outer {_x000D_
display: flex;_x000D_
justify-content: center_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
Apply Autoprefixer for all browser support:
#outer {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center
}
Use transform:
#inner {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
transform: translate(-50%)_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
With Autoprefixer:
#inner {
position: absolute;
left: 50%;
-webkit-transform: translate(-50%);
-ms-transform: translate(-50%);
transform: translate(-50%)
}
This error can also happen if you pass a key word argument for which one of the keys is similar (has same string name) to a positional argument.
>>> class Foo():
... def bar(self, bar, **kwargs):
... print(bar)
...
>>> kwgs = {"bar":"Barred", "jokes":"Another key word argument"}
>>> myfoo = Foo()
>>> myfoo.bar("fire", **kwgs)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() got multiple values for argument 'bar'
>>>
"fire" has been accepted into the 'bar' argument. And yet there is another 'bar' argument present in kwargs.
You would have to remove the keyword argument from the kwargs before passing it to the method.
A TCP/IP connection is always made to an IP address (you can think of an IP-address as the address of a certain computer, even if that is not always the case) and a specific (logical, not physical) port on that address.
Usually one port is coupled to a specific process or "service" on the target computer. Some port numbers are standardized, like 80 for http, 25 for smtp and so on. Because of that standardization you usually don't need to put port numbers into your web adresses.
So if you say something like http://www.stackoverflow.com, the part "stackoverflow.com" resolves to an IP address (in my case 64.34.119.12) and because my browser knows the standard it tries to connect to port 80 on that address. Thus this is the same as http://www.stackoverflow.com:80.
But there is nothing that stops a process to listen for http requests on another port, like 12434, 4711 or 8080. Usually (as in your case) this is used for debugging purposes to not intermingle with another process (like IIS) already listening to port 80 on the same machine.
Yes, you can do <property name="defaultLocale" value="#{ systemProperties['user.region']}"/>
for instance.
The variable systemProperties is predefined, see 6.4.1 XML based configuration.
There are two things,
1) You can run the mongodb instance without username and password first.
2) Then you can add the user to the system database of the mongodb which is default one using the query below.
db.createUser({
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
Thanks.
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
I just closed all the files and reopened them, and voila!!! Hope this helps someone in the future ;)
I had this issue when my appdelegate class was not linked against my main app target but a separate static framework. Linking it directly against the target app fixed the issue.
This is what has worked for me in order to disable CORS between Spring boot and React
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* Overriding the CORS configuration to exposed required header for ussd to work
*
* @param registry CorsRegistry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(4800);
}
}
I had to modify the Security configuration also like below:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
}).and()
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().accessDeniedHandler(apiAccessDeniedHandler());
}
sourceString.Replace(removeString, "");
how about
echo $list | grep -w -q $x
you could either check the output or $?
of above line to make the decision.
grep -w
checks on whole word patterns. Adding -q
prevents echoing the list.
In that case, you don't need to use angular.copy()
Explanation :
=
represents a reference whereas angular.copy()
creates a new object as a deep copy.
Using =
would mean that changing a property of response.data
would change the corresponding property of $scope.example
or vice versa.
Using angular.copy()
the two objects would remain seperate and changes would not reflect on each other.
Use the vbcrlf
for new line in SSSR. e.g.
= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1")
If you need to create a user_id
then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:
rails generate migration AddUserRefToProducts user:references
This command will generate the following migration:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :user, :product, index: true
end
end
After running rake db:migrate
both a user_id
column and an index will be added to the products
table.
In case you just need to add an index to an existing column, e.g. name
of a user
table, the following technique may be helpful:
rails generate migration AddIndexToUsers name:string:index
will generate the following migration:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_index :users, :name
end
end
Delete add_column
line and run the migration.
In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index
command and then delete add_column
line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:
rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references
DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
it doesn't has any means? you may be just need to add like this!
<IfModule dir_module>
DirectoryIndex index.php index.html index.htm
</IfModule>
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
the first way is better, the second way cost more time on creating a new array and converting to a list
Include <%@ page isELIgnored="false"%>
on top of your jsp page.
This is how I do it:
std::string removeAll(std::string str, char c) {
size_t offset = 0;
size_t size = str.size();
size_t i = 0;
while (i < size - offset) {
if (str[i + offset] == c) {
offset++;
}
if (offset != 0) {
str[i] = str[i + offset];
}
i++;
}
str.resize(size - offset);
return str;
}
Basically whenever I find a given char, I advance the offset and relocate the char to the correct index. I don't know if this is correct or efficient, I'm starting (yet again) at C++ and i'd appreciate any input on that.
'so many subjective answers to an objective question. "Unobtrusive" JavaScript is superstition like the old rule to never use gotos. Write code in a way that helps you reliably accomplish your goal, not according to someone's trendy religious beliefs.
Anyone who finds:
<body onload="body_onload();">
to be overly distracting is overly pretentious and doesn't have their priorities straight.
I normally put my JavaScript code in a separate .js file, but I find nothing cumbersome about hooking event handlers in HTML, which is valid HTML by the way.
This worked for me.
<table>
<tr>
<td *ngFor="#group of groups">
<h1>{{group.name}}</h1>
</td>
</tr>
</table>
I am trying to do that in jQuery 2.1, and with the "$().click() -> $(element).data("events").click;
" method it doesn't work.
I realized that only the $._data() functions works in my case :
$(document).ready(function(){_x000D_
_x000D_
var node = $('body');_x000D_
_x000D_
// Bind 3 events to body click_x000D_
node.click(function(e) { alert('hello'); })_x000D_
.click(function(e) { alert('bye'); })_x000D_
.click(fun_1);_x000D_
_x000D_
// Inspect the events of body_x000D_
var events = $._data(node[0], "events").click;_x000D_
var ev1 = events[0].handler // -> function(e) { alert('hello')_x000D_
var ev2 = events[1].handler // -> function(e) { alert('bye')_x000D_
var ev3 = events[2].handler // -> function fun_1()_x000D_
_x000D_
$('body')_x000D_
.append('<p> Event1 = ' + eval(ev1).toString() + '</p>')_x000D_
.append('<p> Event2 = ' + eval(ev2).toString() + '</p>')_x000D_
.append('<p> Event3 = ' + eval(ev3).toString() + '</p>'); _x000D_
_x000D_
});_x000D_
_x000D_
function fun_1() {_x000D_
var txt = 'text del missatge'; _x000D_
alert(txt);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
</body>
_x000D_
Try with :
echo "To: [email protected]" > /var/www/report.csv
echo "Subject: Subject" >> /var/www/report.csv
echo "MIME-Version: 1.0" >> /var/www/report.csv
echo "Content-Type: text/html; charset=\"us-ascii\"" >> /var/www/report.csv
echo "Content-Disposition: inline" >> /var/www/report.csv
echo "<html>" >> /var/www/report.csv
mysql -u ***** -p***** -H -e "select * from users LIMIT 20" dev >> /var/www/report.csv
echo "</html>" >> /var/www/report.csv
mail -s "Built notification" [email protected] < /var/www/report.csv
I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:
/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
R.drawable.srilanka, R.drawable.pakistan,
};
private void initializeImageList() {
// TODO Auto-generated method stub
for (int i = 0; i < imageIconDatabase.length; i++) {
map = new HashMap<String, Object>();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
}
}
My implementation
/// <summary>
/// Sending file via multipart\form-data
/// </summary>
/// <param name="url">URL for send</param>
/// <param name="file">Local file path</param>
/// <param name="paramName">Request file param</param>
/// <param name="contentType">Content-Type file headr</param>
/// <param name="nvc">Additional post params</param>
private static string httpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
//delimeter
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//creating request
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
//sending request
using(var requestStream = wr.GetRequestStream())
{
using (var requestWriter = new StreamWriter(requestStream, Encoding.UTF8))
{
//params
const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
requestWriter.Write(boundary);
requestWriter.Write(String.Format(formdataTemplate, key, nvc[key]));
}
requestWriter.Write(boundary);
//file header
const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
requestWriter.Write(String.Format(headerTemplate, paramName, file, contentType));
//file content
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(requestStream);
}
requestWriter.Write("\r\n--" + boundary + "--\r\n");
}
}
//reading response
try
{
using (var wresp = (HttpWebResponse)wr.GetResponse())
{
if (wresp.StatusCode == HttpStatusCode.OK)
{
using (var responseStream = wresp.GetResponseStream())
{
if (responseStream == null)
return null;
using (var responseReader = new StreamReader(responseStream))
{
return responseReader.ReadToEnd();
}
}
}
throw new ApplicationException("Error while upload files. Server status code: " + wresp.StatusCode.ToString());
}
}
catch (Exception ex)
{
throw new ApplicationException("Error while uploading file", ex);
}
}
document.location
isn't a string.
You're probably wanting to use document.location.href
or document.location.pathname
instead.
If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:
float:left; display:inline; width: 49%;
on both of them.
#mainContent, #sideContent {float:left; display:inline; width: 49%;}
It is not (with current browsers) possible to make an input field read-only through CSS alone.
Though, as you have already mentioned, you can apply the attribute readonly='readonly'
.
If your main criteria is to not alter the markup in the source, there are ways to get this in, unobtrusively, with javascript.
With jQuery, this is easy:
$('input').attr('readonly', true);
Or even with plain Javascript:
document.getElementById('someId').setAttribute('readonly', 'readonly');
Bootstrap rows always contain their floats and create new lines. You don't need to worry about filling blank columns, just make sure they don't add up to more than 12.
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-3 col-xs-offset-9">_x000D_
I'm a right column of 3_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-3">_x000D_
I'm a left column of 3_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div class="panel-body">_x000D_
And I'm some content below both columns_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.
MyType result;
SimpleUsing.DoUsing(db =>
{
result = db.SomeQuery(); //whatever returns the MyType result
});
//do something with result
I'd add Commons NullComparator instead to avoid some problems...
You could find the difference between dates in columns in a data frame by using the function difftime
as follows:
df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))
The slightly modified version of COPY
below worked better for me, where I specify the CSV
format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT
.
COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );
Try with this one:
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
$("#content").load($(this).attr('href'));
});
});
and make sure to call this library first:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
While agf was right with the answer in the past, now with PEP-3124 we got our syntactic sugar.
See typing documentation for details on the @overload
decorator, but note that this is really just syntactic sugar and IMHO this is all people have been arguing about ever since.
Personally, I agree that having multiple functions with different signatures makes it more readable then having a single function with 20+ arguments all set to a default value (None
most of the time) and then having to fiddle around using endless if
, elif
, else
chains to find out what the caller actually wants our function to do with the provided set of arguments. This was long overdue following the Python Zen:
Beautiful is better than ugly.
and arguably also
Simple is better than complex.
Straight from the official Python documentation linked above:
from typing import overload
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> Tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>
For those who (unlike OP) are using the express lib:
http.get('*',function(req,res){
res.redirect('http://exmple.com'+req.url)
})
I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
String inputLine = "";
/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/
FileInputStream fIn = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
try {
/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/
FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
Since I never can remember that LINQ calls it Where
, Select
and Aggregate
instead of Filter
, Map
and Reduce
so I created a few extension methods you can use:
IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
return self.Select(selector);
}
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
return self.Where(predicate);
}
Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :
Hi recently looked into this and had issues referencing the named table (list object) within excel
if you place a suffix '$' on the table name all is well in the world
Sub testSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
' Declare variables
strFile = ThisWorkbook.FullName
' construct connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
' create connection and recordset objects
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' open connection
cn.Open strCon
' construct SQL query
strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"
' execute SQL query
rs.Open strSQL, cn
Debug.Print rs.GetString
' close connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
I had the same problem, but caused by Homebrew:
[~]$ rbenv version
2.3.0 (set by /Users/user/.rbenv/version)
[~]$ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]
[~]$ which ruby
/usr/local/bin/ruby
Somehow I had installed Ruby via Homebrew too, and the Homebrew path was ahead of the rbenv path in my $PATH
. Running brew uninstall ruby
fixed it for me.
The connectivity: package does not guarantee the actual internet connection (could be just wifi connection without internet access).
Quote from the documentation:
Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.
If you really need to check the connection to the www Internet the better choice would be
The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,
def lower_wick_vec(o, l, c):
min_oc = numpy.where(o > c, c, o)
return min_oc - l
where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:
def lower_wick_df(df):
min_oc = df[['Open', 'Close']].min(axis=1)
return min_oc - l
The other three will work on columns or vectors just as they are. Then you can finish off with
def is_hammer(df):
lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"])
cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
return cl & lw
Bit operators can perform set logic on boolean vectors, &
for and
, |
for or
etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.
For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.
I resolved this problem by following steps:
may be it help you to.
There is another library called arrow
really great to make manipulation on python date.
import arrow
import datetime
a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
DISTINCT
is the keyword
For me your query is correct
Just try to do this first
SELECT DISTINCT title,id FROM tbl_countries
Later on you can try with order by.
In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.
Using absolute path should be the best solution:
import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')
var element = document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
elemRect = element.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
You could do like this:
SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));
Call WinAPI function (if u are developing win-application)
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
This method is deprecated now from now starting with Android Q.
Try This will really help.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
btnOnOff.setText("Wifi ONN");
} else {
wifiManager.setWifiEnabled(false);
btnOnOff.setText("Wifi OFF");
}
} else {// if it is Android Q and above go for the newer way NOTE: You can also use this code for less than android Q also
Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
startActivityForResult(panelIntent, 1);
}
There are several other ways, besides using the in
operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
UIImage *ui =resultimg.image;
pasteboard.image = ui;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
}
The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery
library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.
is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require
it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.
Imagine the following project structure:
project |-- node_modules |-- public | |-- css | |-- img | |-- js | |-- index.html |-- package.json
In your index.html
you can reference both css
and js
files like this:
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
Which is the simplest way, and correct for the .css
files. But it is much better to include the bootstrap.js
file like this somewhere in your public/js/*.js
files:
var bootstrap = require('bootstrap');
And you include this code only in those javascript
files where you actually need bootstrap.js
. Browserify takes care of including this file for you.
Now, the drawback is that you now have your front-end files as node_modules
dependencies, and the node_modules
folder is usually not checked in with git
. I think this is the most controversial part, with many opinions and solutions.
Almost two years have passed since I wrote this answer and an update is in place.
Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.
Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:
const bootstrap = require('bootstrap');
As for the css
files, webpack has so called "loaders". They allow you write this in your js code:
require('bootstrap/dist/css/bootstrap.css');
and the css files will be "magically" included in your build.
They will be dynamically added as <style />
tags when your app runs, but you can configure webpack to export them as a separate css
file. You can read more about that in webpack's documentation.
In conclusion.
node_modules
nor the dynamically built files to git. You can add a build
script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.It is very straight forward
HTML
<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>
jQuery
$(document).ready(function(){
$('.button').css( 'cursor', 'pointer' );
// for old IE browsers
$('.button').css( 'cursor', 'hand' );
});
Do you mean any specific syntax for wildcards? Usually *
stands for "one or many" characters and ?
stands for one.
The simplest way probably is to translate a wildcard expression into a regular expression, then use that for filtering the results.
easily kick out the problem by just add this line both try and catch block
path: node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js
bson = require('bson'); instead
bson = require('./win32/ia32/bson');
bson = require('../build/Release/bson');
That is all!!!
import codecs
...
fichier = codecs.open(filePath, "r", encoding="utf-8")
...
fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)
...
You can groupby the 'name'
and 'month'
columns, then call transform
which will return data aligned to the original df and apply a lambda where we join
the text entries:
In [119]:
df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
df[['name','text','month']].drop_duplicates()
Out[119]:
name text month
0 name1 hej,du 11
2 name1 aj,oj 12
4 name2 fin,katt 11
6 name2 mycket,lite 12
I sub the original df by passing a list of the columns of interest df[['name','text','month']]
here and then call drop_duplicates
EDIT actually I can just call apply
and then reset_index
:
In [124]:
df.groupby(['name','month'])['text'].apply(lambda x: ','.join(x)).reset_index()
Out[124]:
name month text
0 name1 11 hej,du
1 name1 12 aj,oj
2 name2 11 fin,katt
3 name2 12 mycket,lite
update
the lambda
is unnecessary here:
In[38]:
df.groupby(['name','month'])['text'].apply(','.join).reset_index()
Out[38]:
name month text
0 name1 11 du
1 name1 12 aj,oj
2 name2 11 fin,katt
3 name2 12 mycket,lite
I got the same problem when toggling the accordion. But when I try to put the script block in the header block, it works for my case!!
<head>
...
<link rel="stylesheet" href="../assets/css/bootstrap.css" />
<script src="../assets/js/jquery-1.9.1.min.js" ></script>
<script src="../assets/js/bootstrap.js" ></script>
</head>
If you specify CSS attributes for your body
element it should apply to anything within <body></body>
so long as you don't override them later in the stylesheet.
Similar to tight_layout
matplotlib now (as of version 2.2) provides constrained_layout
. In contrast to tight_layout
, which may be called any time in the code for a single optimized layout, constrained_layout
is a property, which may be active and will optimze the layout before every drawing step.
Hence it needs to be activated before or during subplot creation, such as figure(constrained_layout=True)
or subplots(constrained_layout=True)
.
Example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(4,4, constrained_layout=True)
plt.show()
constrained_layout may as well be set via rcParams
plt.rcParams['figure.constrained_layout.use'] = True
See the what's new entry and the Constrained Layout Guide
If you want it visually formatted to two decimals as a string (for output) use toFixed()
:
var priceString = someValue.toFixed(2);
The answer by @David has two problems:
It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999
instead of "134.20"
.
If your value is an integer or rounds to one tenth, you will not see the additional decimal value:
var n = 1.099;
(Math.round( n * 100 )/100 ).toString() //-> "1.1"
n.toFixed(2) //-> "1.10"
var n = 3;
(Math.round( n * 100 )/100 ).toString() //-> "3"
n.toFixed(2) //-> "3.00"
And, as you can see above, using toFixed()
is also far easier to type. ;)
I'm blind, and have been programming for about 13 years on Windows, Mac, Linux and DOS, in languages from C/C++, Python, Java, C# and various smaller languages along the way. Though the original question was around configuring the environment, I think it's best answered by looking at how a blind person would use a computer.
Some people use a talking environment, such as T. V. Raman and the Emacspeak environment mentioned in other answers. The more common solution by far is to have a screen reader which runs in the background monitoring OS activity and alerting the user via synthetic speech or a physical braille display (generally showing somewhere from 20 to 80 characters at a time). This then means a blind person can use any accessible application.
So, I personally use Visual Studio 2008 these days, and run it with very few modifications. I turn off certain features like displaying errors as I type since I find this distracting. Prior to joining Microsoft all my development was done in a standard text editor like Notepad, so once again no customisations.
It is possible to configure a screen reader to announce indentation. I personally don't use this, since Visual Studio takes care of this, and C# uses braces. But this would be very important in a language like Python where whitespace matters. Finally, Emacspeak does make use of different voices/pitches to indicate different parts of syntax (keywords, comments, identifiers, etc).
As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.
I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.
This alternative approach uses SQL Server's OUTER APPLY
clause. This way, it
The OUTER APPLY
clause can be imagined as a LEFT JOIN
, but with the advantage that you can use values of the main query as parameters in the subquery (here: game).
SELECT colMinPointID
FROM (
SELECT game
FROM table
GROUP BY game
) As rstOuter
OUTER APPLY (
SELECT TOP 1 id As colMinPointID
FROM table As rstInner
WHERE rstInner.game = rstOuter.game
ORDER BY points
) AS rstMinPoints
There are two issues here.
Firstly, you can't use the []
syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.
data.put
is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:
public class Data {
public static void main(String[] args) {
Map<String, String> data = new HashMap<String, String>();
data.put("John", "Taxi Driver");
data.put("Mark", "Professional Killer");
}
}
If you want to initialize a map as a static field of a class then you can use Map.of
, since Java 9:
public class Data {
private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}
Before Java 9, you can use a static initializer block to accomplish the same thing:
public class Data {
private static final Map<String, String> DATA = new HashMap<>();
static {
DATA.put("John", "Taxi Driver");
}
}
$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
$IP
}
Get-content Filename returns an array of strings for each line.
On the first string only, I split it based on ",". Dumping it into $IP_Array.
$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
if ($IP -eq "2.2.2.2") {
Write-Host "Found $IP"
}
}
My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.
To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.
The relevel()
command is a shorthand method to your question. What it does is reorder the factor so that whatever is the ref level is first. Therefore, reordering your factor levels will also have the same effect but gives you more control. Perhaps you wanted to have levels 3,4,0,1,2. In that case...
bFactor <- factor(b, levels = c(3,4,0,1,2))
I prefer this method because it's easier for me to see in my code not only what the reference was but the position of the other values as well (rather than having to look at the results for that).
NOTE: DO NOT make it an ordered factor. A factor with a specified order and an ordered factor are not the same thing. lm()
may start to think you want polynomial contrasts if you do that.
Add vertical-align: middle;
to the td
element that contains the button
<td style="vertical-align:middle;"> <--add this to center vertically
<a href="#" class="btn btn-primary">
<i class="icon-check icon-white"></i>
</a>
</td>
Of course.
That is normal and sane behaviour.
Instead of closing and re-opening, you could rewind
the file.
boolval()
works for complicated tables where declaring variables and adding loops and filters do not work. Example:
$result[$row['name'] . "</td><td>" . (boolval($row['special_case']) ? 'True' : 'False') . "</td><td>" . $row['more_fields'] = $tmp
where $tmp
is a key used in order to transpose other data. Here, I wanted the table to display "Yes" for 1 and nothing for 0, so used (boolval($row['special_case']) ? 'Yes' : '')
.
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
You can just split the string..
public String[] split(String regex)
Note that java.lang.String.split uses delimiter's regular expression value. Basically like this...
String filename = "abc.def.ghi"; // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0]; // Text before the first dot
Of course, this is split into multiple lines for clairity. It could be written as
String beforeFirstDot = filename.split("\\.")[0];
If you installed rspec as a plugin rather than as a gem, then you won't have the spec
executable.
At any rate, All you need to do is run the file using ruby. The rspec code is clever enough to run the tests for you.
eg:
ruby myclass_spec.rb
The right solution is to use grep -v "word" file
, with its awk
equivalent:
awk '!/word/' file
However, if you happen to have a more complex situation in which you want, say, XXX
to appear and YYY
not to appear, then awk
comes handy instead of piping several grep
s:
awk '/XXX/ && !/YYY/' file
# ^^^^^ ^^^^^^
# I want it |
# I don't want it
You can even say something more complex. For example: I want those lines containing either XXX
or YYY
, but not ZZZ
:
awk '(/XXX/ || /YYY/) && !/ZZZ/' file
etc.