Add the icon to the project resources and rename to icon.
Open the designer of the form you want to add the icon to.
Append the InitializeComponent function.
Add this line in the top:
this.Icon = PROJECTNAME.Properties.Resources.icon;
repeat step 4 for any forms in your project you want to update
You do this via attributes on the properties, like this:
[Description("Test text displayed in the textbox"),Category("Data")]
public string Text {
get => myInnerTextBox.Text;
set => myInnerTextBox.Text = value;
}
The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.
I agree with using events for this. Since I suspect that you're building an MDI-application (since you create many child forms) and creates windows dynamically and might not know when to unsubscribe from events, I would recommend that you take a look at Weak Event Patterns. Alas, this is only available for framework 3.0 and 3.5 but something similar can be implemented fairly easy with weak references.
However, if you want to find a control in a form based on the form's reference, it's not enough to simply look at the form's control collection. Since every control have it's own control collection, you will have to recurse through them all to find a specific control. You can do this with these two methods (which can be improved).
public static Control FindControl(Form form, string name)
{
foreach (Control control in form.Controls)
{
Control result = FindControl(form, control, name);
if (result != null)
return result;
}
return null;
}
private static Control FindControl(Form form, Control control, string name)
{
if (control.Name == name) {
return control;
}
foreach (Control subControl in control.Controls)
{
Control result = FindControl(form, subControl, name);
if (result != null)
return result;
}
return null;
}
You can do it without modifying the XML stream: Tell the XmlReader to not be so picky.
Setting the XmlReaderSettings.ConformanceLevel
to ConformanceLevel.Fragment
will let the parser ignore the fact that there is no root node.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(tr,settings))
{
...
}
Now you can parse something like this (which is an real time XML stream, where it is impossible to wrap with a node).
<event>
<timeStamp>1354902435238</timeStamp>
<eventId>7073822</eventId>
</event>
<data>
<time>1354902435341</time>
<payload type='80'>7d1300786a0000000bf9458b0518000000000000000000000000000000000c0c030306001b</payload>
</data>
<data>
<time>1354902435345</time>
<payload type='80'>fd1260780912ff3028fea5ffc0387d640fa550f40fbdf7afffe001fff8200fff00f0bf0e000042201421100224ff40312300111400004f000000e0c0fbd1e0000f10e0fccc2ff0000f0fe00f00f0eed00f11e10d010021420401</payload>
</data>
<data>
<time>1354902435347</time>
<payload type='80'>fd126078ad11fc4015fefdf5b042ff1010223500000000000000003007ff00f20e0f01000e0000dc0f01000f000000000000004f000000f104ff001000210f000013010000c6da000000680ffa807800200000000d00c0f0</payload>
</data>
Try this:
str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
Output:
ice
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2
:
1,000.46
But in Germany you would change comma and point:
1.000,46
This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure
of the Zend Framework for this task. This component will parse the string to a float by the users language.
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething
gives you a "pointer to member function" which refers to the member function but not the associated object.
There are two ways around this, one is to use std::bind
to bind the "pointer to member function" to the this
pointer. The other is to use a lambda that captures the this
pointer and calls the member function.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};
I would prefer the latter.
With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function
will result in dynamic memory allocation.
On the other hand, a lambda that captures this
is only one pointer in size, assigning it to an std::function
will not result in dynamic memory allocation with g++.
While I have not verified this with other compilers, I suspect similar results will be found there.
For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.
You could try this :
"okay.this.is.a.string".split(".").join("")
Greetings
Just ssh'ing to the host is not enough, on Windows at least. That adds the host key to ssh/known_hosts
but the error still persists.
You need to close the git bash window and open a new one. Then the registry cache is cleared and the push/pull then works.
Old question, but still relevant. Here is what worked for me today (6/26/16).
From the bash shell:
lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg
install apt-cyg /bin
If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.
Piecing things together from here and other places, this is what I came up with that works on unbuntu 12.04 and centOS6
Create an file in /etc/rsyslog.d/
that ends in .conf and add the following text
local6.* /var/log/my-logfile
Restart rsyslog
, reloading did NOT seem to work for the new log files. Maybe it only reloads existing conf files?
sudo restart rsyslog
Then you can use this test program to make sure it actually works.
import logging, sys
from logging import config
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(module)s P%(process)d T%(thread)d %(message)s'
},
},
'handlers': {
'stdout': {
'class': 'logging.StreamHandler',
'stream': sys.stdout,
'formatter': 'verbose',
},
'sys-logger6': {
'class': 'logging.handlers.SysLogHandler',
'address': '/dev/log',
'facility': "local6",
'formatter': 'verbose',
},
},
'loggers': {
'my-logger': {
'handlers': ['sys-logger6','stdout'],
'level': logging.DEBUG,
'propagate': True,
},
}
}
config.dictConfig(LOGGING)
logger = logging.getLogger("my-logger")
logger.debug("Debug")
logger.info("Info")
logger.warn("Warn")
logger.error("Error")
logger.critical("Critical")
If you want to keep the general styling (rounded corners etc.) and just change the background color then I use the backgroundTint property
android:backgroundTint="@android:color/holo_green_light"
This is how I do it:
with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
stripped = (line.strip() for line in infile)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(outfile)
writer.writerows(lines)
Hope it helps!
I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.
As per the official documentation, there are four ways, you can allow complete access for robots to access your site.
Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt
looks like this.
User-agent: *
Disallow:
Create a /robots.txt
file with no content in it. Which will default to allow all for all type of Bots
.
Do not create a /robots.txt
altogether. Which should yield the exact same results as the above two.
From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots
know that these pages are not supposed to be indexed.
<META NAME="ROBOTS" CONTENT="NOINDEX">
In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD
tag of the page. More about this meta tag here.
MySQL has supported the ROW_NUMBER() since version 8.0+.
If you use MySQL 8.0 or later, check it out ROW_NUMBER() function. Otherwise, you have emulate ROW_NUMBER() function.
The row_number() is a ranking function that returns a sequential number of a row, starting from 1 for the first row.
for older version,
SELECT t.*,
@rowid := @rowid + 1 AS ROWID
FROM TABLE t,
(SELECT @rowid := 0) dummy;
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
The trick is to give padding on the td
elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):
td {
padding-top:20px;
padding-bottom:20px;
padding-right:20px;
}
td:first-child {
padding-left:20px;
padding-right:0;
}
First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child
You can use the same reasoning for the horizontal padding by using tr:first-child td
.
Alternatively, exclude the first column by using the not
operator. Support for this is not as good right now, though.
td:not(:first-child) {
padding-top:20px;
padding-bottom:20px;
padding-right:20px;
}
Use theme()
:
d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20),
axis.text.x = element_text(angle=90, hjust=1))
#vjust adjust the vertical justification of the labels, which is often useful
There's lots of good information about how to format your ggplots here. You can see a full list of parameters you can modify (basically, all of them) using ?theme
.
You can activate JVM's debugging capability when starting up the java
command with a special option:
java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar
Starting up jar.jar
like that on the command line will:
server=y
) listening on port 8000 (address=8000
)Listening for transport dt_socket at address: 8000
to stdout
andsuspend=y
) until some debugger connects. The debugger acts as the client in this scenario.Common options for selecting a debugger are:
jar.jar
should begin executing.jdb -connect com.sun.jdi.SocketAttach:port=8000
Clear Resharper cache: Resharper -> Options -> General -> Clear Caches, close and reopen the solution. It worked in R# 9.0 Update 1
One of the reasons of this problem might be "Build Active Architecture Only". You need set to true.
To get the list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP
If you gave a title to your stash, replace "WIP" in -grep=WIP
at the end of the command with a part of your message, e.g. -grep=Tesselation
.
The command is grepping for "WIP" because the default commit message for a stash is in the form WIP on mybranch: [previous-commit-hash] Message of the previous commit.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
When I had the same problem I fixed it by deleting the existing key.snk
in that project and adding a new key.
I just had this problem myself under Debian Wheezy. I restarted the adb daemon with sudo:
sudo ./adb kill-server
sudo ./adb start-server
sudo ./adb devices
Everything is working :)
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
i'd like to share mine, i have been following this anti forgerytoken tutorial
using asp.net mvc 4 with angularjs, but it throws an exception everytime i request using $http.post and i figured out the solution is just add
'X-Requested-With': 'XMLHttpRequest' to the headers of $http.post, because it seems like the (filterContext.HttpContext.Request.IsAjaxRequest())
does not recognize it as ajax and here is my example code.
App.js
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'RequestVerificationToken': $scope.token,
'Content-Type': 'application/json; charset=utf-8;'
};
$http({
method: 'POST',
url: baseURL + 'Save/User',
data: JSON.stringify($scope.formData),
headers: headers
}).then(function (values) {
alert(values.data);
}).catch(function (err) {
console.log(err.data);
});
SaveController
[HttpPost]
[MyValidateAntiForgeryToken]
public ActionResult User(UserModel usermodel)
{
....
Ctrl + Shift + P
Then type and click on > preferences:configure language specific settings
and then type "python" after that. Paste the code
{
"python.linting.pylintArgs": [
"--load-plugins=pylint_django", "--errors-only"
],
}
It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
$('#content').toggle('show');
});
});
</script>
And the html
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
Of course, the accepted answer of Arrays.equal( byte[] first, byte[] second ) is correct. I like to work at a lower level, but I was unable to find a low level efficient function to perform equality test ranges. I had to whip up my own, if anyone needs it:
public static boolean ArraysAreEquals(
byte[] first,
int firstOffset,
int firstLength,
byte[] second,
int secondOffset,
int secondLength
) {
if( firstLength != secondLength ) {
return false;
}
for( int index = 0; index < firstLength; ++index ) {
if( first[firstOffset+index] != second[secondOffset+index]) {
return false;
}
}
return true;
}
I was finally able to get this to work for my needs.
The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.
https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.
The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.
Private Sub MySubNamek()
Dim objShell As Object 'Shell
Dim objFolder As Object 'Folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")
If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
For i = 0 To 288
szItem = objFolder.GetDetailsOf(objFolderItem, i)
Debug.Print i & " - " & szItem
Next
Set objFolderItem = Nothing
End If
Set objFolder = Nothing
Set objShell = Nothing
End Sub
Is simple,
YourModel.objects.filter(YOUR_DATE_FIELD__date=timezone.now())
Works for me
As of Notepad++ 6.9, the new Folder as Workspace feature can be used.
Folder as Workspace opens your folder(s) in a panel so you can browse folder(s) and open any file in Notepad++. Every changement in the folder(s) from outside will be synchronized in the panel. Usage: Simply drop 1 (or more) folder(s) in Notepad++.
This feature has the advantage of not showing your entire file system when just the working directory is needed. It also means you don't need plugins for it to work.
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.
If you care about reading that will always return the objects in the order they are inserted in a Dictionary, you may have a look at
OrderedDictionary - values can be accessed via an integer index (by order in which items were added) SortedDictionary - items are automatically sorted
Yes you can do this without absolute
positioning and without using table
s (which screw with markup and such).
DEMO
This is tested to work on IE>7, chrome, FF & is a really easy thing to add to your existing layout.
<div id="container">
Some content you don't want affected by the "bottom floating" div
<div>supports not just text</div>
<div class="foot">
Some other content you want kept to the bottom
<div>this is in a div</div>
</div>
</div>
#container {
height:100%;
border-collapse:collapse;
display : table;
}
.foot {
display : table-row;
vertical-align : bottom;
height : 1px;
}
It effectively does what float:bottom
would, even accounting for the issue pointed out in @Rick Reilly's answer!
This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)
JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest
and the associated browser methods. Instead a <script>
tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head>
element).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// success
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.
{ "bar": "baz" }
foo( { "bar": "baz" } );
This is why you see JSONP requests containing the callback
parameter, so that the server knows the name of the function to wrap the response.
This function must exist in the global scope at the time the <script>
tag is evaluated by the browser (once the request has completed).
Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.
Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.
The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.
By default jQuery requires you to include &callback=?
in the URL of your AJAX request. jQuery will take the success
function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ?
in &callback=?
with the name it has assigned.
The following assumes a response object { "bar" : "baz" }
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
function foo(response) {
document.getElementById("output").innerHTML = response.bar;
};
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
You can use it to transform some aggregate functions into analytic:
SELECT MAX(date)
FROM mytable
will return 1
row with a single maximum,
SELECT MAX(date) OVER (ORDER BY id)
FROM mytable
will return all rows with a running maximum.
You need rawQuery method.
Example:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
Use ? bindings instead of putting values into raw sql query.
As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:
import pandas as pd
import numpy as np
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
which displays
This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:
constants.name = ['pie','eek']
C
However it appears to have some limitations:
Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):
constants.loc[2] = dict(name='bogus', value=123.456)
constants['comment'] = ['fee','fie','fo']
constants
which looks ok but:
C
Formatting works only for values, not index entries:
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
constants.set_index('name',inplace=True)
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
Please follow the steps below :
Based on 4 and 5, execute one of the commands (Do not execute all of them without reading above description):
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer
sudo xcode-select -s /[XCODE-ACTUAL-LOCATION]/Xcode.app/Contents/Developer
sudo xcode-select -s /[XCODE-ACTUAL-LOCATION]/Xcode-beta.app/Contents/Developer
Simply saying, Java context means Java native
methods all together.
In next Java code two lines of code needs context: // (1)
and // (2)
import java.io.*;
public class Runner{
public static void main(String[] args) throws IOException { // (1)
File file = new File("D:/text.txt");
String text = "";
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null){ // (2)
text += line;
}
System.out.println(text);
}
}
(1) needs context because is invoked by Java native method private native void java.lang.Thread.start0();
(2) reader.readLine()
needs context because invokes Java native method public static native void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
PS.
That is what BalusC is sayed about pattern Facade more strictly.
You shouldn't re-open the source file each time you do a copy, better open it once and pass the resulting BinaryReader to the copy function. Also, it might help if you order your seeks, so you don't make big jumps inside the file.
If the lengths aren't too big, you can also try to group several copy calls by grouping offsets that are near to each other and reading the whole block you need for them, for example:
offset = 1234, length = 34
offset = 1300, length = 40
offset = 1350, length = 1000
can be grouped to one read:
offset = 1234, length = 1074
Then you only have to "seek" in your buffer and can write the three new files from there without having to read again.
In case you are into functional this is a function written in Scala showing how you could copy an input stream to an output stream using only vals (and not vars).
def copyInputToOutputFunctional(inputStream: InputStream, outputStream: OutputStream,bufferSize: Int) {
val buffer = new Array[Byte](bufferSize);
def recurse() {
val len = inputStream.read(buffer);
if (len > 0) {
outputStream.write(buffer.take(len));
recurse();
}
}
recurse();
}
Note that this is not recommended to use in a java application with little memory available because with a recursive function you could easily get a stack overflow exception error
For those have HashMap based spinner :
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
If you are in a Fragment, an Adaptor or a Class other than main activities , use this:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
It's just for guidance; you should find your view's id before onClick method.
Device: iPad Mini
OS: iOS 9 Beta 3
App downloaded from: Hockey App
Provisioning profile with Trust issues: Enterprise
In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.
Here are the steps that I followed:
That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)
You did two mistakes . I think you misplace FROM and WHERE keywords.
SELECT DISTINCT Description, Date as treatmentDate
FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I --Here you use "." operator to "I" alias
WHERE -- WHERE should be located here.
P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
You could read Google answer for it here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
cout << "inside loop body: " << i << endl;
}
Try to create remote origin first, maybe is missing because you change name of the remote repo
git remote add origin URL_TO_YOUR_REPO
You can also use, if you want to preserve exit error status, and have a readable file with one command per line:
my_command1 || exit $?
my_command2 || exit $?
This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.
You can rename the directory using the file system. Then you can do git rm <old directory>
and git add <new directory>
(Help page). Then you can commit and push.
Git will detect that the contents are the same and that it's just a rename operation, and it'll appear as a rename entry in the history. You can check that this is the case before the commit using git status
Sorry that was a typo. You can either add node_modules to the end of your user's global path variable, or maybe check the permissions associated with that folder (node _modules). The error doesn't seem like the last case, but I've encountered problems similar to yours. I find the first solution enough for most cases. Just go to environment variables and add the path to node_modules to the last part of your user's path variable. Note I'm saying user and not system.
Just add a semicolon to the end of the variable declaration and add the static path to your node_module folder. ( Ex c:\path\to\node_module)
Alternatively you could:
In your CMD
PATH=%PATH%;C:\\path\to\node_module
EDIT
The last solution will work as long as you don't close your CMD. So, use the first solution for a permanent change.
As other people have already said this isn't supported in the C language. You could however check the size of a variable using the sizeof()
function. This may help you determine if two variables can store the same type of data.
Before you do that, read the comments below.
Here is the comparison between MD5 and SHA1. You can get a clear idea about which one is better.
It is wrong to say that one is a better choice than the other (or both wouldn't have been given their own purpose in the spec). It may even be worth noting that StackOverflow makes extensive use of px units. It is not the poor choice Spoike was told it was.
Definition of units
px is an absolute unit of measurement (like in, pt, or cm) that also happens to be 1/96 of an in unit (more on why later). Because it is an absolute measurement, it may be used any time you want to define something to be a particular size, rather than being proportional to something else like the size of the browser window or the font size.
Like all the other absolute units, px units don't scale according to the width of the browser window. Thus, if your entire page design uses absolute units such as px rather than %, it won't adapt to the width of the browser. This is not inherently good or bad, just a choice that the designer needs to make between adhering to an exact size and being inflexible versus stretching but in the process not adhering to an exact size. It would be typical for a site to have a mix of fixed-size and flexible-sized objects.
Fixed size elements often need to be incorporated into the page - such as advertising banners, logos or icons. This ensures you almost always need at least some px-based measurements in a design. Images, for example, will (by default) be scaled such that each pixel is 1*px* in size, so if you are designing around an image you'll need px units. It is also very useful for precise font sizing, and for border widths, where due to rounding it makes the most sense to use px units for the majority of screens.
All absolute measurements are rigidly related to each other; that is, 1in is always 96px, just as 1in is always 72pt. (Note that 1in is almost never actually a physical inch when talking about screen-based media). All absolute measurements assume a nominal screen resolution of 96ppi and a nominal viewing distance of a desktop monitor, and on such a screen one px will be equal to one physical pixel on the screen and one in will be equal to 96 physical pixels. On screens that differ significantly in either pixel density or viewing distance, or if the user has zoomed the page using the browser's zoom function, px will no longer necessarily relate to physical pixels.
em is not an absolute unit - it is a unit that is relative to the currently chosen font size. Unless you have overridden font style by setting your font size with an absolute unit (such as px or pt), this will be affected by the choice of fonts in the user's browser or OS if they have made one, so it does not make sense to use em as a general unit of length except where you specifically want it to scale as the font size scales.
Use em when you specifically want the size of something to depend on the current font size.
% is also a relative unit, in this case, relative to either the height or width of a parent element. They are a good alternative to px units for things like the total width of a design if your design does not rely on specific pixel sizes to set its size.
Using % units in your design allows your design to adapt to the width of the screen/device, whereas using an absolute unit such as px does not.
If you are looking for this:
Here is the link:
http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
If we have this variables:
var counter int = 5
var message string = "Hello"
var factor float32 = 4.2
var enabled bool = false
1: fmt.Printf %T format : to use this feature you should import "fmt"
fmt.Printf("%T \n",factor ) // factor type: float32
2: reflect.TypeOf function : to use this feature you should import "reflect"
fmt.Println(reflect.TypeOf(enabled)) // enabled type: bool
3: reflect.ValueOf(X).Kind() : to use this feature you should import "reflect"
fmt.Println(reflect.ValueOf(counter).Kind()) // counter type: int
I'm a little late to the party, but maybe this could help. The link in the question had a similar formula, but mine uses the IF() statement to get rid of errors.
If you're not afraid of Ctrl+Shift+Enter, you can do pretty well with an array formula.
String (in cell A1): "one.two.three.four"
Formula:
{=MAX(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)))} use Ctrl+Shift+Enter
Result: 14
First,
ROW($1:$99)
returns an array of integers from 1 to 99: {1,2,3,4,...,98,99}
.
Next,
MID(A1,ROW($1:$99),1)
returns an array of 1-length strings found in the target string, then returns blank strings after the length of the target string is reached: {"o","n","e",".",..."u","r","","",""...}
Next,
IF(MID(I16,ROW($1:$99),1)=".",ROW($1:$99))
compares each item in the array to the string "." and returns either the index of the character in the string or FALSE: {FALSE,FALSE,FALSE,4,FALSE,FALSE,FALSE,8,FALSE,FALSE,FALSE,FALSE,FALSE,14,FALSE,FALSE.....}
Last,
=MAX(IF(MID(I16,ROW($1:$99),1)=".",ROW($1:$99)))
returns the maximum value of the array: 14
Advantages of this formula is that it is short, relatively easy to understand, and doesn't require any unique characters.
Disadvantages are the required use of Ctrl+Shift+Enter and the limitation on string length. This can be worked around with a variation shown below, but that variation uses the OFFSET() function which is a volatile (read: slow) function.
Not sure what the speed of this formula is vs. others.
Variations:
=MAX((MID(A1,ROW(OFFSET($A$1,,,LEN(A1))),1)=".")*ROW(OFFSET($A$1,,,LEN(A1)))) works the same way, but you don't have to worry about the length of the string
=SMALL(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)),2) determines the 2nd occurrence of the match
=LARGE(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)),2) determines the 2nd-to-last occurrence of the match
=MAX(IF(MID(I16,ROW($1:$99),2)=".t",ROW($1:$99))) matches a 2-character string **Make sure you change the last argument of the MID() function to the number of characters in the string you wish to match!
In my case, I forgot to add library jackson-core.jar, I only added jackson-annotations.jar and jackson-databind.jar. When I added jackson-core.jar, it fixed the problem.
| ATTENTION !!! |
Get from Yahoo a JSON or XML that you can parse from a REST query.
You can exchange from any to any currency and even get the date and time of the query using the YQL (Yahoo Query Language).
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dnl1d1t1%26s%3Dusdeur%3DX%22%3B&format=json&callback=
This will bring an example like below:
{
"query": {
"count": 1,
"created": "2016-02-12T07:07:30Z",
"lang": "en-US",
"results": {
"row": {
"col0": "USD/EUR",
"col1": "0.8835",
"col2": "2/12/2016",
"col3": "7:07am"
}
}
}
}
You can try the console
I think this does not break any Term of Service as it is a 100% yahoo solution.
http://jsfiddle.net/marcosfromero/aWyNn/
$('#yourdiv'). // Get your box ...
dialog(). // ... and turn it into dialog (autoOpen: false also works)
prev('.ui-dialog-titlebar'). // Get title bar,...
find('a'). // ... then get the X close button ...
hide(); // ... and hide it
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({_x000D_
crossOrigin: true,_x000D_
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})
_x000D_
Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size
div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}
I can find one in macOS Mojave (10.14) while playing with virtualenvwrapper-4.8.4
/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
@media all and (max-width:320px)and(min-width:0px) {
#container {
width: 100%;
}
sty {
height: 50%;
width: 100%;
text-align: center;
margin: 0;
}
}
.username {
margin-bottom: 20px;
margin-top: 10px;
}
EDIT: Updated for the latest version of nodemon!
I was struggling with the same thing for my development environment until I noticed that nodemon
's API allows us to change its default behaviour in order to execute a custom command. For example:
nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts
Or even better: externalize nodemon's config to a nodemon.json
file with the following content, and then just run nodemon
, as Sandokan suggested:
{ "watch": ["src/**/*.ts"], "ignore": ["src/**/*.spec.ts"], "exec": "ts-node ./index.ts" }
By virtue of doing this, you'll be able to live-reload a ts-node
process without having to worry about the underlying implementation.
Cheers!
Updated for the most recent version of nodemon:
You can run this, for example:
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "ts-node src/index.ts"
Or create a nodemon.json
file with the following content:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/index.ts" // or "npx ts-node src/index.ts"
}
and then run nodemon
with no arguments.
You must first import the functions:
import org.apache.spark.sql.functions._
Then you can use them like this:
val df = CSV.load(args(0))
val sumSteps = df.agg(sum("steps")).first.get(0)
You can also cast the result if needed:
val sumSteps: Long = df.agg(sum("steps").cast("long")).first.getLong(0)
Edit:
For multiple columns (e.g. "col1", "col2", ...), you could get all aggregations at once:
val sums = df.agg(sum("col1").as("sum_col1"), sum("col2").as("sum_col2"), ...).first
Edit2:
For dynamically applying the aggregations, the following options are available:
df.groupBy().sum()
val columnNames = List("col1", "col2")
df.groupBy().sum(columnNames: _*)
val cols = List("col1", "col2")
val sums = cols.map(colName => sum(colName).cast("double").as("sum_" + colName))
df.groupBy().agg(sums.head, sums.tail:_*).show()
Alternative: Check out the code in SVN to some folder
You can get the filecount like so:
$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
$filecount = count($files);
}
echo "There were $filecount files";
where the "*"
is you can change that to a specific filetype if you want like "*.jpg"
or you could do multiple filetypes like this:
glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)
the GLOB_BRACE
flag expands {a,b,c} to match 'a', 'b', or 'c'
I like to use the recursive pattern for this scenario. For example, something like this:
// If config is an array of queries
var config = JSON.parse(queries.querrryArray);
// Array of results
var results;
processQueries(config);
function processQueries(queries) {
var searchQuery;
if (queries.length == 0) {
// All queries complete
res.writeHead(200, {'content-type': 'application/json'});
res.end(JSON.stringify({results: results}));
return;
}
searchQuery = queries.pop();
search(searchQuery, function(result) {
results.push(JSON.stringify({result: result});
processQueries();
});
}
processQueries
is a recursive function that will pull a query element out of an array of queries to process. Then the callback function calls processQueries
again when the query is complete. The processQueries
knows to end when there are no queries left.
It is easiest to do this using arrays, but it could be modified to work with object key/values I imagine.
Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.
THen, send your ip + port to the person who will use it.
I had the same problem.
Here is a workaround
android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"
To call the function on click of some html element (control).
$('#controlID').click(myFunction);
You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready
$(document).ready(function(){
$('#controlID').click(myFunction);
});
You can use anonymous function to bind the event to the html element.
$(document).ready(function(){
$('#controlID').click(function(){
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
});
});
If you want to bind click with many elements you can use class selector
$('.someclass').click(myFunction);
Edit based on comments by OP, If you want to call function under some condition
You can use if for conditional execution, for example,
if(a == 3)
myFunction();
I was having trouble installing tensorflow with python 3.7 and followed these instructions to have a virtual environment setup with python3.6 and got it working
Download the Python3.6 tgz file from the official website (eg. Python-3.6.6.tgz)
Unpack it with tar -xvzf Python-3.6.6.tgz
cd Python-3.6.6
run ./configure
run make altinstall to install it (install vs altinstall explanation here
setting up python3.6 virtual environment for tensorflow
If you are using jupyter notebook or jupyter lab this can be helpful to choose the right virtual environment
python -m venv projectname
source projectname/bin/activate
pip install ipykernel
ipython kernel install --user --name=projectname
At this point, you can start jupyter, create a new notebook and select the kernel that lives inside your environment.
virtual environment and jupyter notebooks
Hope this helps
Because the view must return render
, not just call it. Change the last line to
return render(request, 'auth_lifecycle/user_profile.html',
context_instance=RequestContext(request))
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
pkill NAMEofAPP
Non rooted marshmallow, termux & terminal emulator.
DECIMAL
has two parts: Precision
and Scale
. So part of your query will look like this:
CAST((COUNT(*) * 1.5) AS DECIMAL(8,2))
Precision
represents the number of significant digits that are stored for values.
Scale
represents the number of digits that can be stored following the decimal point.
Python is not the best tool for this task. I tried several approaches in Python but none of them work 100% (e.g. 10% converts to 0.1, or column types are messed up, etc). The right tool here is PowerShell, because it is an MS product (as is Excel) and has the best integration.
Simply download this PowerShell script, edit line 47 to enter the path for the folder containing the Excel files and run the script using PowerShell.
Make sure you switch to default content before switching to frame:
driver.switchTo().defaultContent();
driver.switchTo().frame(x);
x
can be the frame number or you can do a driver.findlement
and use any of the options you have available eg: driver.findElementByName("Name")
.
Assuming that Array's length is constant. In Javascript, This is what we do:
const intialArray = new Array(specify the value);
You are checking it the array index contains a string "undefined"
, you should either use the typeof
operator:
typeof predQuery[preId] == 'undefined'
Or use the undefined
global property:
predQuery[preId] === undefined
The first way is safer, because the undefined
global property is writable, and it can be changed to any other value.
One way, provide --user
flag as part of curl
, as follows:
curl --user username:password http://example.com
Another way is to get Base64 encoded token of "username:password" from any online website like - https://www.base64encode.org/ and pass it as Authorization
header of curl
as follows:
curl -i -H 'Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=' http://localhost:8080/
Here, dXNlcm5hbWU6cGFzc3dvcmQ=
is Base64
encoded token of username:password
.
In addition to the intuitive explanation Chris Smith has provided, we can consider why this is the case from a different perspective: considering undirected graphs.
To see why in a DIRECTED graph the answer is n*(n-1)
, consider an undirected graph (which simply means that if there is a link between two nodes (A and B) then you can go in both ways: from A to B and from B to A). The maximum number of edges in an undirected graph is n(n-1)/2
and obviously in a directed graph there are twice as many.
Good, you might ask, but why are there a maximum of n(n-1)/2
edges in an undirected graph?
For that, Consider n points (nodes) and ask how many edges can one make from the first point. Obviously, n-1
edges. Now how many edges can one draw from the second point, given that you connected the first point? Since the first and the second point are already connected, there are n-2
edges that can be done. And so on. So the sum of all edges is:
Sum = (n-1)+(n-2)+(n-3)+...+3+2+1
Since there are (n-1)
terms in the Sum, and the average of Sum in such a series is ((n-1)+1)/2
{(last + first)/2}, Sum = n(n-1)/2
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
Some IDEs highlight the code in heredoc strings automatically - which makes using heredoc for XML or HTML visually appealing.
I personally like it for longer parts of i.e. XML since I don't have to care about quoting quote characters and can simply paste the XML.
This should work in pretty much any browser...
function getByClass (className, parent) {
parent || (parent=document);
var descendants=parent.getElementsByTagName('*'), i=-1, e, result=[];
while (e=descendants[++i]) {
((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
}
return result;
}
You should be able to use it like this:
function replaceInClass (className, content) {
var nodes = getByClass(className), i=-1, node;
while (node=nodes[++i]) node.innerHTML = content;
}
This is how I count TABLES and ALL RECORDS using PHP:
$dtb = mysql_query("SHOW TABLES") or die (mysql_error());
$jmltbl = 0;
$jml_record = 0;
$jml_record = 0;
while ($row = mysql_fetch_array($dtb)) {
$sql1 = mysql_query("SELECT * FROM " . $row[0]);
$jml_record = mysql_num_rows($sql1);
echo "Table: " . $row[0] . ": " . $jml_record record . "<br>";
$jmltbl++;
$jml_record += $jml_record;
}
echo "--------------------------------<br>$jmltbl Tables, $jml_record > records.";
After deleting data from list view, you have to call refreshDrawableState()
.
Here is the example:
final DatabaseHelper db = new DatabaseHelper (ActivityName.this);
db.open();
db.deleteContact(arg3);
mListView.refreshDrawableState();
db.close();
and deleteContact
method in DatabaseHelper
class will be somewhat looks like
public boolean deleteContact(long rowId) {
return db.delete(TABLE_NAME, BaseColumns._ID + "=" + rowId, null) > 0;
}
you can just do
select rownum, l.* from student l where name like %ram%
this assigns the row number as the rows are fetched (so no guaranteed ordering of course).
if you wanted to order first do:
select rownum, l.*
from (select * from student l where name like %ram% order by...) l;
This will show only Cart Items Count.
global $woocommerce;
echo $woocommerce->cart->cart_contents_count;
This is a handy function for getting filenames, with the specified format (usually .mat
) in a root folder!
function filenames = getFilenames(rootDir, format)
% Get filenames with specified `format` in given `foler`
%
% Parameters
% ----------
% - rootDir: char vector
% Target folder
% - format: char vector = 'mat'
% File foramt
% default values
if ~exist('format', 'var')
format = 'mat';
end
format = ['*.', format];
filenames = dir(fullfile(rootDir, format));
filenames = arrayfun(...
@(x) fullfile(x.folder, x.name), ...
filenames, ...
'UniformOutput', false ...
);
end
In your case, you can use the following snippet :)
filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
filename = filenames{i};
% do your job!
end
As such, it is desirable to split the dataset into train and test sets in a way that preserves the same proportions of examples in each class as observed in the original dataset.
This is called a stratified train-test split.
We can achieve this by setting the “stratify” argument to the y component of the original dataset. This will be used by the train_test_split() function to ensure that both the train and test sets have the proportion of examples in each class that is present in the provided “y” array.
You can do this using Escape Sequence.
\"
So you will have to write something like this :
String name = "\"john\"";
You can learn about Escape Sequences from here.
NSLog(@"%@", CGRectCreateDictionaryRepresentation(rect));
Try this, It supports multi file uploading,
$('#multi_file_upload').change(function(e) {
var file_id = e.target.id;
var file_name_arr = new Array();
var process_path = site_url + 'public/uploads/';
for (i = 0; i < $("#" + file_id).prop("files").length; i++) {
var form_data = new FormData();
var file_data = $("#" + file_id).prop("files")[i];
form_data.append("file_name", file_data);
if (check_multifile_logo($("#" + file_id).prop("files")[i]['name'])) {
$.ajax({
//url : site_url + "inc/upload_image.php?width=96&height=60&show_small=1",
url: site_url + "inc/upload_contact_info.php",
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
type: 'post',
success: function(data) {
// display image
}
});
} else {
$("#" + html_div).html('');
alert('We only accept JPG, JPEG, PNG, GIF and BMP files');
}
}
});
function check_multifile_logo(file) {
var extension = file.substr((file.lastIndexOf('.') + 1))
if (extension === 'jpg' || extension === 'jpeg' || extension === 'gif' || extension === 'png' || extension === 'bmp') {
return true;
} else {
return false;
}
}
Here #multi_file_upload is the ID of image upload field.
There are a few Java-based XML diff and merge tools listed here:
Open Source XML Diff written in Java
Added links:
StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1);
string methodName = caller.GetMethod().Name;
will be enough, I think.
Set an intermediate page where you change $_POST variables into $_SESSION. In your actual page, unset them after usage.
You may pass also the initial page URL to set the browser back button.
A very simple solution: replace https:// with git://
Use git://the.repository instead of https://the.repository and will work.
I've had this problem on Windows with TortoiseGit and this solved it.
If you are running the program with python, try running it with python3.
Because 1
is numeric, but not integer (i.e. it's a floating point number), and 1:6000
is numeric and integer.
> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"
60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:
> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
3.6 billion is easily representable in floating point, however:
> as.single(60000)*as.single(60000)
[1] 3.6e+09
To fix your for
code, convert to a floating point representation:
function (N)
{
for(i in as.single(1:N)) {
y <- i*i
}
}
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
You can find and kill the running processes: ps aux | grep puma
Then you can kill it with kill PID
The key here is to unlist the row first.
colnames(DF) <- as.character(unlist(DF[1,]))
DF = DF[-1, ]
I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.
java.lang.IllegalArgumentException: No enum constant
Also the problem was when we at Parcelize read moment write some short if.
My solution for this was
1.Create companion object with parsing method.
enum class CarsType {
@Json(name = "SMALL")
SMALL,
@Json(name = "BIG")
BIG;
companion object {
fun nullableValueOf(name: String?) = when (name) {
null -> null
else -> valueOf(name)
}
}
}
2. In Parcerable read place use it like this
data class CarData(
val carId: String? = null,
val carType: CarsType?,
val data: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
CarsType.nullableValueOf(parcel.readString()),
parcel.readString())
I think that this should work:
.element {
-webkit-transition: all .3s;
-moz-transition: all .3s;
-o-transition: all .3s;
transition: all .3s;
}
In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.
For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:
Function cleanString(text As String) As String
Dim output As String
Dim c 'since char type does not exist in vba, we have to use variant type.
For i = 1 To Len(text)
c = Mid(text, i, 1) 'Select the character at the i position
If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
output = output & c 'add the character to your output.
Else
output = output & " " 'add the replacement character (space) to your output
End If
Next
cleanString = output
End Function
The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.
This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.
I realized a Open Source library on GitHub CircularProgressBar that does exactly what you want the simplest way possible:
To make a circular ProgressBar add CircularProgressBar in your layout XML and add CircularProgressBar library in your projector or you can also grab it via Gradle:
compile 'com.mikhaellopez:circularprogressbar:1.0.0'
<com.mikhaellopez.circularprogressbar.CircularProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:background_progressbar_color="#FFCDD2"
app:background_progressbar_width="5dp"
app:progressbar_color="#F44336"
app:progressbar_width="10dp" />
You must use the following properties in your XML to change your CircularProgressBar.
Properties:
app:progress
(integer) >> default 0app:progressbar_color
(color) >> default BLACKapp:background_progressbar_color
(color) >> default GRAYapp:progressbar_width
(dimension) >> default 7dpapp:background_progressbar_width
(dimension) >> default 3dpCircularProgressBar circularProgressBar = (CircularProgressBar)findViewById(R.id.yourCircularProgressbar);
circularProgressBar.setColor(ContextCompat.getColor(this, R.color.progressBarColor));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(this, R.color.backgroundProgressBarColor));
circularProgressBar.setProgressBarWidth(getResources().getDimension(R.dimen.progressBarWidth));
circularProgressBar.setBackgroundProgressBarWidth(getResources().getDimension(R.dimen.backgroundProgressBarWidth));
int animationDuration = 2500; // 2500ms = 2,5s
circularProgressBar.setProgressWithAnimation(65, animationDuration); // Default duration = 1500ms
Fork or Download this library here >> https://github.com/lopspower/CircularProgressBar
in the foreign key table has a value that is not owned in the primary key table that will be related, so you must delete all data first / adjust the value of your foreign key table according to the value that is in your primary key
First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.
> is.numeric(1)
[1] TRUE
> is.integer(1)
[1] FALSE
> is.numeric(1L)
[1] TRUE
> is.integer(1L)
[1] TRUE
(Putting capital 'L' after an integer forces it to be stored as an integer.)
As you can see "integer" is a subset of "numeric".
> .Machine$integer.max
[1] 2147483647
> .Machine$double.xmax
[1] 1.797693e+308
Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).
Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.
One thing to watch out for is that the colon operator, :
, will return integers if the start and end points are whole numbers. For example, 1:5
creates an integer
vector of numbers from 1 to 5. You don't need to append the letter L
.
> class(1:5)
[1] "integer"
Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R
enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.
In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg
The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:
em.persist(abc);
em.flush();
return abc.getId();
or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.
@Override
public ABC addNewABC(ABC abc) {
abcDao.insertABC(abc);
return abc;
}
Use pyplot.suptitle
or Figure.suptitle
:
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
ax=fig.add_subplot(2,2,i)
ax.imshow(data)
fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()
If you want to clear the data but keep the headers:
$('#myTableId tbody').empty();
The table must be formatted in this manner:
<table id="myTableId">
<thead>
<tr>
<th>header1</th><th>header2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data1</td><td>data2</td>
</tr>
</tbody>
</table>
Please check this answer
// In angularJS script
$scope.foo = function() {
console.log('test');
};
$window.angFoo = function() {
$scope.foo();
$scope.$apply();
};
// In jQuery
if (window.angFoo) {
window.angFoo();
}
How about:
import pandas as pd
#List with all words
words=[]
#Code for adding words
words.append('test')
#When Input equals blank:
pd.Series(words).nunique()
It returns how many unique values are in a list
I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads()
function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...
I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [
or curly {
bracket. No images formats I know of start with those characters.
Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.
Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).
A simple extension method for this would be:
public static void AddParameter(this SqlCommand sqlCommand, string parameterName,
SqlDbType sqlDbType, object item)
{
sqlCommand.Parameters.Add(parameterName, sqlDbType).Value = item ?? DBNull.Value;
}
This happened to me and I found a solution, see if this works for you:
Once you have built your project with the hammer icon:
Afterwards you should be able to run the project as much as you'd like.
Hopefully this works for you.
My inclination was to add this as an extension to NSAttributedString
rather than String
. I tried it as a static extension and an initializer. I prefer the initializer which is what I've included below.
Swift 4
internal convenience init?(html: String) {
guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
return nil
}
guard let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
return nil
}
self.init(attributedString: attributedString)
}
Swift 3
extension NSAttributedString {
internal convenience init?(html: String) {
guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
return nil
}
guard let attributedString = try? NSMutableAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
return nil
}
self.init(attributedString: attributedString)
}
}
Example
let html = "<b>Hello World!</b>"
let attributedString = NSAttributedString(html: html)
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
htons
is host-to-network short
This means it works on 16-bit short integers. i.e. 2 bytes.
This function swaps the endianness of a short.
Your number starts out at:
0001 0011 1000 1001 = 5001
When the endianness is changed, it swaps the two bytes:
1000 1001 0001 0011 = 35091
a.sort(function(a,b){return a - b})
These can be confusing.... check this link out.
If U want commit to a new empty Repo ,You can checkout the new empty Repo and commit to new remote repo.
chekout a new empty Repo won't delete your local files.
try this:
for example,
remote repo url : https://example.com/SVNTest
cd [YOUR PROJECT PATH]
rm -rf .svn
svn co https://example.com/SVNTest ../[YOUR PROJECT DIR NAME]
svn add ./*
svn ci -m"changed repo url"
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
use a static defaultProps like:
export default class AddAddressComponent extends Component {
static defaultProps = {
provinceList: [],
cityList: []
}
render() {
let {provinceList,cityList} = this.props
if(cityList === undefined || provinceList === undefined){
console.log('undefined props')
}
...
}
AddAddressComponent.contextTypes = {
router: React.PropTypes.object.isRequired
}
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
}
AddAddressComponent.propTypes = {
userInfo: React.PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
Taken from: https://github.com/facebook/react-native/issues/1772
If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.
To add on the earlier comments, I would like to say the following :
The setTimeout()
function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.
There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the Date()
function and adding the time interval you need.
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).This will help you.
import java.nio.ByteBuffer;
import java.util.Arrays;
public class MyClass
{
public static void main(String args[]) {
byte [] hbhbytes = ByteBuffer.allocate(4).putInt(16666666).array();
System.out.println(Arrays.toString(hbhbytes));
}
}
For the sake of completeness, there is also a data.table
solution:
library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
# col1 col2 col1_length col2_length
#1: abc adf qqwe 3 8
#2: abcd d 4 1
#3: a e 1 1
#4: abcdefg f 7 1
print "Number of lines: $nids\n";
print "Content: $ids\n";
How did Perl complain? print $ids
should work, though you probably want a newline at the end, either explicitly with print
as above or implicitly by using say
or -l/$\.
If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}
:
print "foo${ids}bar";
Accepted answer is outdated.
If you use MySQL 5.5.3+, use utf8mb4_unicode_ci
instead of utf8_unicode_ci
to ensure the characters typed by your users won't give you errors.
utf8mb4
supports emojis for example, whereas utf8
might give you hundreds of encoding-related bugs like:
Incorrect string value: ‘\xF0\x9F\x98\x81…’ for column ‘data’ at row 1
You can make the copy constructor private and provide no implementation:
private:
SymbolIndexer(const SymbolIndexer&);
Or in C++11, explicitly forbid it:
SymbolIndexer(const SymbolIndexer&) = delete;
Jenkins is the new Hudson. It really is more like a rename, not a fork, since the whole development community moved to Jenkins. (Oracle is left sitting in a corner holding their old ball "Hudson", but it's just a soul-less project now.)
C.f. Ethereal -> WireShark
LESS has guard expressions for mixins, not individual attributes.
So you'd create a mixin like this:
.debug(@debug) when (@debug = true) {
header {
background-color: yellow;
#title {
background-color: orange;
}
}
article {
background-color: red;
}
}
And turn it on or off by calling .debug(true);
or .debug(false)
(or not calling it at all).
I know this is old but...
I found this:
http://javaforge.com/project/schemasel
From the description, after you install the plugin it appears that if you follow the logical connection name with a schema in square brackets, it should connect to the schema by default.
It does but the object browser does not.
Oh well.
You can use a pairwise cyclic iterator:
from itertools import izip, cycle, tee
def pairwise(seq):
a, b = tee(seq)
next(b)
return izip(a, b)
for elem, next_elem in pairwise(cycle(li)):
...
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
The usage from the official documentation:
https://maven.apache.org/plugins/maven-dependency-plugin/usage.html#dependency:get
For my case, see the answer below:
mvn dependency:get -Dartifact=$2:$3:$4:$5 -DremoteRepositories=$1 -Dtransitive=false
mvn dependency:copy -Dartifact=$2:$3:$4:$5 -DremoteRepositories=$1 -Dtransitive=false -DoutputDirectory=$6
#mvn dependency:get -Dartifact=com.huya.mtp:hynswup:1.0.88-SNAPSHOT:jar -DremoteRepositories=http://nexus.google.com:8081/repository/maven-snapshots/ -Dtransitive=false
#mvn dependency:copy -Dartifact=com.huya.mtp:hynswup:1.0.88-SNAPSHOT:jar -DremoteRepositories=http://nexus.google.com:8081/repository/maven-snapshots/ -Dtransitive=false -DoutputDirectory=.
Use the command mvn dependency:get
to download the specific artifact and use
the command mvn dependency:copy
to copy the downloaded artifact to the destination directory -DoutputDirectory
.
Solution: Put libeay32.dll, libssh2.dll, ssleay32.dll files under dir specified in httpd.conf's ServerRoot directive. These dlls can be found compiled under php root folder.
Reasons:
Problem is php_curl.dll requires to access following libraries while loading: libeay32.dll, libssh2.dll, ssleay32.dll and it does not make sense if you put them in ./php/ext dir or if you put php extensions in php root dir.
Of course you can put them in c:\Windows or in some global folder defined in PATH but if you dont want to do this and you want that your apache+php installation was portable:
The path specified in ServerRoot in httpd.conf is treated as home path for php. The behaviour is similar to situation where you include ./path/to/some.php file in ./index.php and home path for some.php file is still ./ the dir where index.php resides.
In shorts just put those three dlls right in dir you specified in httpd.conf ServerRoot directive and php_curl.dll will not fail to load again.
Just incidentally, this is a the least verbose way of turning off all certificate validation in a given app that I know of:
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
vim[grep]
command..:vimgrep /example\c/ &
Probably something like this? (UNTESTED)
Sub Sample()
Dim strWB4, strMyMacro
strMyMacro = "Sheet1.my_macro_name"
'
'~~> Rest of Code
'
'loop through the folder and get the file names
For Each Fil In FLD.Files
Set x4WB = x1.Workbooks.Open(Fil)
x4WB.Application.Visible = True
x1.Run strMyMacro
x4WB.Close
Do Until IsWorkBookOpen(Fil) = False
DoEvents
Loop
Next
'
'~~> Rest of Code
'
End Sub
'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Based on some answers I found here, I made myself a small helper file to source for my projects:
#!/bin/bash
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit $1
}
function catch()
{
export ex_code=$?
(( $SAVED_OPT_E )) && set +e
return $ex_code
}
function throwErrors()
{
set -e
}
function ignoreErrors()
{
set +e
}
here is an example how it looks like in use:
#!/bin/bash
export AnException=100
export AnotherException=101
# start with a try
try
( # open a subshell !!!
echo "do something"
[ someErrorCondition ] && throw $AnException
echo "do something more"
executeCommandThatMightFail || throw $AnotherException
throwErrors # automaticatly end the try block, if command-result is non-null
echo "now on to something completely different"
executeCommandThatMightFail
echo "it's a wonder we came so far"
executeCommandThatFailsForSure || true # ignore a single failing command
ignoreErrors # ignore failures of commands until further notice
executeCommand1ThatFailsForSure
local result = $(executeCommand2ThatFailsForSure)
[ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
executeCommand3ThatFailsForSure
echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
# now you can handle
case $ex_code in
$AnException)
echo "AnException was thrown"
;;
$AnotherException)
echo "AnotherException was thrown"
;;
*)
echo "An unexpected exception was thrown"
throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
;;
esac
}
First and foremost, REST describes a URI as a universally unique ID. Far too many people get caught up on the structure of URIs and which URIs are more "restful" than others. This argument is as ludicrous as saying naming someone "Bob" is better than naming him "Joe" – both names get the job of "identifying a person" done. A URI is nothing more than a universally unique name.
So in REST's eyes arguing about whether ?id=["101404","7267261"]
is more restful than ?id=101404,7267261
or \Product\101404,7267261
is somewhat futile.
Now, having said that, many times how URIs are constructed can usually serve as a good indicator for other issues in a RESTful service. There are a couple of red flags in your URIs and question in general.
Multiple URIs for the same resource and Content-Location
We may want to accept both styles but does that flexibility actually cause more confusion and head aches (maintainability, documentation, etc.)?
URIs identify resources. Each resource should have one canonical URI. This does not mean that you can't have two URIs point to the same resource but there are well defined ways to go about doing it. If you do decide to use both the JSON and list based formats (or any other format) you need to decide which of these formats is the main canonical URI. All responses to other URIs that point to the same "resource" should include the Content-Location
header.
Sticking with the name analogy, having multiple URIs is like having nicknames for people. It is perfectly acceptable and often times quite handy, however if I'm using a nickname I still probably want to know their full name – the "official" way to refer to that person. This way when someone mentions someone by their full name, "Nichloas Telsa", I know they are talking about the same person I refer to as "Nick".
"Search" in your URI
A more complex case is when we want to offer more complex inputs. For example, if we want to allow multiple filters on search...
A general rule of thumb of mine is, if your URI contains a verb, it may be an indication that something is off. URI's identify a resource, however they should not indicate what we're doing to that resource. That's the job of HTTP or in restful terms, our "uniform interface".
To beat the name analogy dead, using a verb in a URI is like changing someone's name when you want to interact with them. If I'm interacting with Bob, Bob's name doesn't become "BobHi" when I want to say Hi to him. Similarly, when we want to "search" Products, our URI structure shouldn't change from "/Product/..." to "/Search/...".
Regarding ["101404","7267261"]
vs 101404,7267261
: My suggestion here is to avoid the JSON syntax for simplicity's sake (i.e. don't require your users do URL encoding when you don't really have to). It will make your API a tad more usable. Better yet, as others have recommended, go with the standard application/x-www-form-urlencoded
format as it will probably be most familiar to your end users (e.g. ?id[]=101404&id[]=7267261
). It may not be "pretty", but Pretty URIs does not necessary mean Usable URIs. However, to reiterate my initial point though, ultimately when speaking about REST, it doesn't matter. Don't dwell too heavily on it.
Your complex search URI example can be solved in very much the same way as your product example. I would recommend going the application/x-www-form-urlencoded
format again as it is already a standard that many are familiar with. Also, I would recommend merging the two.
Your URI...
/Search?term=pumas&filters={"productType":["Clothing","Bags"],"color":["Black","Red"]}
Your URI after being URI encoded...
/Search?term=pumas&filters=%7B%22productType%22%3A%5B%22Clothing%22%2C%22Bags%22%5D%2C%22color%22%3A%5B%22Black%22%2C%22Red%22%5D%7D
Can be transformed to...
/Product?term=pumas&productType[]=Clothing&productType[]=Bags&color[]=Black&color[]=Red
Aside from avoiding the requirement of URL encoding and making things look a bit more standard, it now homogenizes the API a bit. The user knows that if they want to retrieve a Product or List of Products (both are considered a single "resource" in RESTful terms), they are interested in /Product/...
URIs.
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
My problem was having type="application/javascript"
on the <script>
tag for jQuery. IE8 does not like this! If your webpage is HTML5 you don't even need to declare the type, otherwise go with type="text/javascript"
instead.
This error is because
argv # which is argument variable that is holding the variables that you pass with a call to the script.
so now instead
Python abc.py
do
python abc.py yourname {pass the variable that you made to store argv}
Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.
Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:
public void executeSqlScript(Connection conn, File inputFile) {
// Delimiter
String delimiter = ";";
// Create scanner
Scanner scanner;
try {
scanner = new Scanner(inputFile).useDelimiter(delimiter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// Loop through the SQL file statements
Statement currentStatement = null;
while(scanner.hasNext()) {
// Get statement
String rawStatement = scanner.next() + delimiter;
try {
// Execute statement
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
if (currentStatement != null) {
try {
currentStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
currentStatement = null;
}
}
scanner.close();
}
The non-recursive version of the function is not too hard - here it is for integers:
long powi(long x, unsigned n)
{
long p = x;
long r = 1;
while (n > 0)
{
if (n % 2 == 1)
r *= p;
p *= p;
n /= 2;
}
return(r);
}
(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)
@Swapnil Godambe It works for me if JSON.stringfy is removed. That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
edit included the newer across()
syntax
Here's another tidyverse
solution, using filter(across())
or previously filter_at
. The advantage is that you can easily extend to more than one column.
Below also a solution with filter_all
in order to find the string in any column,
using diamonds
as example, looking for the string "V"
library(tidyverse)
# for only one column... extendable to more than one creating a column list in `across` or `vars`!
mtcars %>%
rownames_to_column("type") %>%
filter(across(type, ~ !grepl('Toyota|Mazda', .))) %>%
head()
#> type mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
#> 2 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
#> 3 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
#> 4 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
#> 5 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
#> 6 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
The now superseded syntax for the same would be:
mtcars %>%
rownames_to_column("type") %>%
filter_at(.vars= vars(type), all_vars(!grepl('Toyota|Mazda',.)))
# remove all rows where any column contains 'V'
diamonds %>%
filter(across(everything(), ~ !grepl('V', .))) %>%
head
#> # A tibble: 6 x 10
#> carat cut color clarity depth table price x y z
#> <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
#> 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
#> 3 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
#> 4 0.3 Good J SI1 64 55 339 4.25 4.28 2.73
#> 5 0.22 Premium F SI1 60.4 61 342 3.88 3.84 2.33
#> 6 0.31 Ideal J SI2 62.2 54 344 4.35 4.37 2.71
The now superseded syntax for the same would be:
diamonds %>%
filter_all(all_vars(!grepl('V', .))) %>%
head
I tried to find an across alternative for the following, but I didn't immediately come up with a good solution:
#get all rows where any column contains 'V'
diamonds %>%
filter_all(any_vars(grepl('V',.))) %>%
head
#> # A tibble: 6 x 10
#> carat cut color clarity depth table price x y z
#> <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
#> 2 0.290 Premium I VS2 62.4 58 334 4.2 4.23 2.63
#> 3 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48
#> 4 0.24 Very Good I VVS1 62.3 57 336 3.95 3.98 2.47
#> 5 0.26 Very Good H SI1 61.9 55 337 4.07 4.11 2.53
#> 6 0.22 Fair E VS2 65.1 61 337 3.87 3.78 2.49
Update: Thanks to user Petr Kajzar in this answer, here also an approach for the above:
diamonds %>%
filter(rowSums(across(everything(), ~grepl("V", .x))) > 0)
Put the line
$this->db->order_by("course_name","desc");
at top of your query. Like
$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();
Readin file with file inputstream and append file content to string.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CopyOffileInputStream {
public static void main(String[] args) {
//File file = new File("./store/robots.txt");
File file = new File("swingloggingsscce.log");
FileInputStream fis = null;
String str = "";
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
str += (char) content;
}
System.out.println("After reading file");
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Following advice from comments I utilize Docker systemd documentation to improve this answer. Below procedure doesn't require reboot and is much cleaner.
First create directory and file for custom configuration:
sudo mkdir -p /etc/systemd/system/docker.service.d
sudo $EDITOR /etc/systemd/system/docker.service.d/docker-storage.conf
For docker version before 17.06-ce paste:
[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// --graph="/mnt"
For docker after 17.06-ce paste:
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// --data-root="/mnt"
daemon.json
I recently tried above procedure with 17.09-ce on Fedora 25 and it seem to not work. Instead of that simple modification in /etc/docker/daemon.json
do the trick:
{
"graph": "/mnt",
"storage-driver": "overlay"
}
Despite the method you have to reload configuration and restart Docker:
sudo systemctl daemon-reload
sudo systemctl restart docker
To confirm that Docker was reconfigured:
docker info|grep "loop file"
In recent version (17.03) different command is required:
docker info|grep "Docker Root Dir"
Output should look like this:
Data loop file: /mnt/devicemapper/devicemapper/data
Metadata loop file: /mnt/devicemapper/devicemapper/metadata
Or:
Docker Root Dir: /mnt
Then you can safely remove old Docker storage:
rm -rf /var/lib/docker
Your local branch likely has modifications to it you want to discard. To do this, you'll need to use git reset
to reset the branch head to the last spot that you diverged from the upstream repo's branch. Use git branch -v
to find the sha1 id of the upstream branch, and reset your branch it it using git reset SHA1ID
. Then you should be able to do a git checkout
to discard the changes it left in your directory.
Note: always do this on a backed-up repo. That way you can assure you're self it worked right. Or if it didn't, you have a backup to revert to.
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
Peeyush:
The short answer is:
For a longer answer, you'll need to wait for me to do a full "HowTo" writeup closer to the 9.4 release.
get_the_post_thumbnail function returns html not url of featured image. You should use get_post_thumbnail_id to get post id of featured image and then use wp_get_attachment_image_src to get url of featured image.
Try this:
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 80, 'product_cat' => 'profiler', 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<div class="dvThumb col-xs-4 col-sm-3 col-md-3 profiler-select profiler<?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
<?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($loop->post->ID)); ?>
<?php if($featured_image) { ?>
<img src="<?php $featured_image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">
<?php } ?>
<p><?php the_title(); ?></p>
<span class="price"><?php echo $product->get_price_html(); ?></span>
</div>
<?php endwhile; ?>
This is a much less professional and much more expensive way but it should be easier to understand and more helpful for beginners.
public static float roundFloat(float F, int roundTo){
String num = "#########.";
for (int count = 0; count < roundTo; count++){
num += "0";
}
DecimalFormat df = new DecimalFormat(num);
df.setRoundingMode(RoundingMode.HALF_UP);
String S = df.format(F);
F = Float.parseFloat(S);
return F;
}
With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-service application!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
<context:component-scan base-package="com.*" />
same issue arrived , i solved it by keeping the annotations intact and in dispatcher servlet :: keeping the base package scan as com.*.
this worked for me.
I took Jezzipin's answer and made it so that if you are scrolled when you refresh the page, the correct size applies. Also removed some stuff that isn't necessarily needed.
function sizer() {
if($(document).scrollTop() > 0) {
$('#header_nav').stop().animate({
height:'40px'
},600);
} else {
$('#header_nav').stop().animate({
height:'100px'
},600);
}
}
$(window).scroll(function(){
sizer();
});
sizer();
Asking a Person whether he wants to call or not Dialog..
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class Firstclass extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);
imageViewCall.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
try{
showDialog("0728570527");
} catch (Exception e){
e.printStackTrace();
}
}
});
}
public void showDialog(final String phone) throws Exception {
AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);
builder.setMessage("Ring: " + phone);
builder.setPositiveButton("Ring", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone));
startActivity(callIntent);
dialog.dismiss();
}
});
builder.setNegativeButton("Abort", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
}
});
builder.show();
}
}
Its a silly problem, just make sure that the jdk and jre are latest version. This problem mainly occurs due to the automatic update of java(jre) and the jdk is not supported to that version, this makes problem.
With the latest version of phpmyadmin 5.0.2+ at least
Check that the actual installation was completed correctly,
Mine had been copied over into a sub folder on a linux machine rather that being at the
/usr/share/phpmyadmin/
Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?
I stumbled across the wonderful Non-sucking Service Manager, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.
I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.
In the latest version of Twitter Bootstrap the layout is fluid by default, hence you don't need extra classes to declare your layout as fluid.
You can further refer to -
http://bassjobsen.weblogs.fm/migrate-your-templates-from-twitter-bootstrap-2-x-to-twitter-bootstrap-3/ http://blog.getbootstrap.com/
Use hex(id)[2:]
and int(urlpart, 16)
. There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.
Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode
and b32decode
. You should give True
for both the casefold
and map01
options to b32decode
in case people write down your shortened URLs.
Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)
$("#selectsearch").change(function() {
var action = $(this).val() == "people" ? "user" : "content";
$("#search-form").attr("action", "/search/" + action);
});
Note that you can also use the C99 fixed-width types perfectly well in Objective-C:
#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform
The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h
and inttypes.h
to be useful.
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
You have to pass a function that accepts two parameters, compares them, and returns a number, so assuming you wanted to sort them by ID you would write...
objArray.sort(function(a,b) {
return a.id-b.id;
});
// objArray is now sorted by Id
Put this code where you define recycler view in activity.
rv_list.addOnItemTouchListener(
new RecyclerItemClickListener(activity, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View v, int position) {
Toast.makeText(activity, "" + position, Toast.LENGTH_SHORT).show();
}
})
);
Then make separate class and put this code:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() =>
{
return 55;
});
Console.WriteLine(MyDynamic.MyMethod());
Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.
In PostGIS, for points with latitude and longitude there is geography datatype.
To add a column:
alter table your_table add column geog geography;
To insert data:
insert into your_table (geog) values ('SRID=4326;POINT(longitude latitude)');
4326 is Spatial Reference ID that says it's data in degrees longitude and latitude, same as in GPS. More about it: http://epsg.io/4326
Order is Longitude, Latitude - so if you plot it as the map, it is (x, y).
To find closest point you need first to create spatial index:
create index on your_table using gist (geog);
and then request, say, 5 closest to a given point:
select *
from your_table
order by geog <-> 'SRID=4326;POINT(lon lat)'
limit 5;
Using Subversion with either the Apache module or svnserve. I've been able to perform operations as multiple users using --username
.
Each time you invoke a Subversion command as a 'new' user, your $HOME/.subversion/auth/<authentication-method>/
directory will have a new entry cached for that user (assuming you are able to authenticate with the correct password or authentication method for the server you are contacting as that particular user).
[
stands for single dimension array
Ljava.lang.String
stands for the string class (L followed by class/interface name)
Few Examples:
Class.forName("[D")
-> Array of primitive doubleClass.forName("[[Ljava.lang.String")
-> Two dimensional array of strings.List of notations:
Element Type : Notation
boolean : Z
byte : B
char : C
class or interface : Lclassname
double : D
float : F
int : I
long : J
short : S
On properties,
Check whether radio button is selected for
Run only when user is logged on
If you selected for the above option then that is the reason why it is failed.
so change the option to
Run whether user is logged on or not
OR
In other case, user might have changed his/her login credentials
I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody
<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...
EDIT As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:
<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"
The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.
One possibility could be to use the 'pageshow' -event instead, as described in:
This might be very useful.
Use NestedScrollView
instead of ScrollView
. Support Library 23.1 introduced an OnScrollChangeListener
to NestedScrollView
.
So you can do something like this.
myScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
Log.d("ScrollView","scrollX_"+scrollX+"_scrollY_"+scrollY+"_oldScrollX_"+oldScrollX+"_oldScrollY_"+oldScrollY);
//Do something
}
});
There is a straightforward solution without messing with matplotlib: just pandas.
Tweaking the original example:
table = sql.read_frame(query,connection)
ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)
ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')
Basically, when the secondary_y=True
option is given (eventhough ax=ax
is passed too) pandas.plot
returns a different axes which we use to set the labels.
I know this was answered long ago, but I think this approach worths it.
Okay If you want to change the gutter inside one row, but want those (first and last) inner divs to align with the grid surrounding the .no-gutter
row, you could copy-paste-merge most answers into the following snippet:
.row.no-gutter [class*='col-']:first-child:not(:only-child) {
padding-right: 0;
}
.row.no-gutter [class*='col-']:last-child:not(:only-child) {
padding-left: 0;
}
.row.no-gutter [class*='col-']:not(:first-child):not(:last-child):not(:only-child) {
padding-right: 0;
padding-left: 0;
}
If you like to have a smaller gutter instead of completly none, just change the 0's to what you like... (eg: 5px to get 10px gutter).
System.Web.UI
contained the Pair
class because it was used heavily in ASP.NET 1.1 as an internal ViewState structure.
Update Aug 2017: C# 7.0 / .NET Framework 4.7 provides a syntax to declare a Tuple with named items using the System.ValueTuple
struct.
//explicit Item typing
(string Message, int SomeNumber) t = ("Hello", 4);
//or using implicit typing
var t = (Message:"Hello", SomeNumber:4);
Console.WriteLine("{0} {1}", t.Message, t.SomeNumber);
see MSDN for more syntax examples.
Update Jun 2012: Tuples
have been a part of .NET since version 4.0.
Here is an earlier article describing inclusion in.NET4.0 and support for generics:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
Monkey is right, according to the link given by monkey
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.
I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting
It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?
You could probably fix the code like this
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Integer.parseInt(s); // This is line 19.
System.out.println(tall[i]);
s = in.readLine();
i++;
}
in.close();
You can access the keys with ${!array[@]}
:
bash-4.0$ echo "${!array[@]}"
foo bar
Then, iterating over the key/value pairs is easy:
for i in "${!array[@]}"
do
echo "key :" $i
echo "value:" ${array[$i]}
done
If you know a variable is empty, you could use it as a comment. Of course if it is not empty it will mess up your command.
ls -l ${1# -F is turned off} -a /etc
Question: Is there a simple way to do this in the current release of Python?
Answer: There is no simple (direct) way to do this in the current release of Python.
Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.
Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.
DB to C#
EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());
C# to DB
string dbStatus = ((int)status).ToString();
You can use an alias to automate the solutions provided by others:
[alias]
rms = "!f(){ git rm --cached \"$1\";rm -r \"$1\";git config -f .gitmodules --remove-section \"submodule.$1\";git config -f .git/config --remove-section \"submodule.$1\";git add .gitmodules; }; f"
Put that in your git config, and then you can do: git rms path/to/submodule
The file you give is a shell script, not an awk program. So, try sh my.awk
.
If you want to use awk -f my.awk life.csv > life_out.cs
, then remove awk -F , '
and the last line from the file and add FS=","
in BEGIN
.
Since I've been looking for this forever, and I found a solution a while ago which is missing here, I'm gonna write it here, for future reference also.
Note: this code was taken directly from Google Android Lollipop dialer a while back, I don't remember If changes were made at the time. Also, I don't know which license is this under, but I have reason to think it is Apache 2.0
.
Class ResizeTextView
, the actual View
public class ResizeTextView extends TextView {
private final int mOriginalTextSize;
private final int mMinTextSize;
private final static int sMinSize = 20;
public ResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mOriginalTextSize = (int) getTextSize();
mMinTextSize = (int) sMinSize;
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize);
}
This ResizeTextView
class could extend TextView and all its children as I undestand, so EditText as well.
Class ViewUtil
with method resizeText(...)
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.graphics.Paint;
import android.util.TypedValue;
import android.widget.TextView;
public class ViewUtil {
private ViewUtil() {}
public static void resizeText(TextView textView, int originalTextSize, int minTextSize) {
final Paint paint = textView.getPaint();
final int width = textView.getWidth();
if (width == 0) return;
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, originalTextSize);
float ratio = width / paint.measureText(textView.getText().toString());
if (ratio <= 1.0f) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
Math.max(minTextSize, originalTextSize * ratio));
}
}
}
You should set your view as
<yourpackage.yourapp.ResizeTextView
android:layout_width="match_parent"
android:layout_height="64dp"
android:gravity="center"
android:maxLines="1"/>
Hope it helps!
i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.
$("label[for='"+$(this).attr("id")+"']");
This should allow you to select labels for all the fields in a loop as well. All you need to ensure is your labels should say for='FIELD'
where FIELD
is the id of the field for which this label is being defined.