After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
I would try fossil scm and the Chisel hosting service
simple, self contained and easily interchangeable with git should you desire in future
had a similiar issue on a server but the SVN directory was very large , didn't want to delete and resync so I just made a copy of the files locally and then deleted them. When update succeeded and added files back in.
After some investigation about file dates I solved the same issue (which is a randomly recurrent trouble on my Kepler) by simply deleting the following file in my local workspace: .metadata.plugins\org.eclipse.jdt.core\variablesAndContainers.dat
with negligible impact on the workspace restoring.
I hope it can help someone else...
Delete the .keyring file under the location: configuration\org.eclipse.core.runtime, and after that, you will be invited to prompt your new svn account. for me it worked.
It is probably of little help to you, but I enter that URL into Subclipse and the repository adds fine and I can browse and Show History on it.
Do you perhaps need to configure a proxy? You have to configure that in the Subversion runtime configuration area as Subclipse uses the Subversion libraries to connect to the server.
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.
Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that "go well together".
I can see that the accepted answer uses position: absolute;
instead of float: left
. In case you want to use float: left
with the following structure,
<div class="parent">
<div class="child-left floatLeft"></div>
<div class="child-right floatLeft"></div>
</div>
Give position: auto;
to the parent so that it will contain its children height.
.parent {
position: auto;
}
.floatLeft {
float: left
}
Here's the Swift 3 way to queue work after a delay.
DispatchQueue.main.asyncAfter(
DispatchTime.now() + DispatchTimeInterval.seconds(2)) {
// do work
}
select * from mytable where mydate > now() - interval '1 year';
If you only care about the date and not the time, substitute current_date
for now()
You should be able to do this if you create the column using the GUI in Management Studio. I believe Management studio is actually completely recreating the table, which is why this appears to happen.
As others have mentioned, the order of columns in a table doesn't matter, and if it does there is something wrong with your code.
Following worked for me:
If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
https://stackoverflow.com/a/16018733/5810078.
(But I have actually copied all the possible files from
C:\Windows\System32\WindowsPowerShell\v1.0\
to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\
(For copying you need to alter the security permissions of that folder))
In System.Diagnostics
,
Debug.Write()
Debug.WriteLine()
etc. will print to the Output window in VS.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).I created a bundle with 3 apps for the finder toolbar. The other two apps do:
For more information see here: http://nslog.de/posts/71
Try with:
$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
Not sure if this would have a faster computational time, but another option...
$acceptedFormats = array('gif', 'png', 'jpg');
if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
echo 'error';
}
Just tell request that you are using json:true and forget about header and parse
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
and the same for post
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
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)
You can use the maven-shade-plugin.
After configuring the shade plugin in your build the command mvn package
will create one single jar with all dependencies merged into it.
The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.
Think of the container as something is invisible to your code, magically providing for its needs, without being asked.
Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.
Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); //format it as per your requirement
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=> " + dateNow);
I was struggling with the same issue and the solution in my case was to log in to the developer account(s). After updating to Xcode 10 all accounts were logged out.
Use the menu "Xcode -> Preferences ... -> Accounts" and make sure all accounts you use are logged in so the provisioning profiles are accessible.
A simple solution for a delayed auto submit:
<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
<form action="https://www.google.com" name="frm1">
<input type="hidden" name="q" value="Hello world" />
</form>
</body>
As a complement to the answer of @martin-r one should note that it is possible to use the sum/difference formula for arcus tangens.
angle = atan2(vec2.y, vec2.x) - atan2(vec1.y, vec1.x);
angle = -atan2(vec1.x * vec2.y - vec1.y * vec2.x, dot(vec1, vec2))
where dot = vec1.x * vec2.x + vec1.y * vec2.y
Also, you can overwrite some variables:
s = input('UPPER CASE')
lower = s.lower()
If you use like this:
s = "Kilometer"
print(s.lower()) - kilometer
print(s) - Kilometer
It will work just when called.
The earlier answer works, but the solution can actually be simpler. Looping through the configured networks list is not required as you get the network id when you add the network through the WifiManager.
So the complete, simplified solution would look something like this:
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
A quick update: since Typescript 2.1 there is a built in type Record<T, K>
that acts like a dictionary.
In this case you could declare stuff like so:
var stuff: Record<string, any> = {};
You could also limit/specify potential keys by unioning literal types:
var stuff: Record<'a'|'b'|'c', string|boolean> = {};
Here's a more generic example using the record type from the docs:
// For every properties K of type T, transform it to U
function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>
const names = { foo: "hello", bar: "world", baz: "bye" };
const lengths = mapObject(names, s => s.length); // { foo: number, bar: number, baz: number }
TypeScript 2.1 Documentation on Record<T, K>
The only disadvantage I see to using this over {[key: T]: K}
is that you can encode useful info on what sort of key you are using in place of "key" e.g. if your object only had prime keys you could hint at that like so: {[prime: number]: yourType}
.
Here's a regex I wrote to help with these conversions. This will only convert cases where the label is "key". To convert other labels simply change the first capturing group:
Find: \{\s*\[(key)\s*(+\s*:\s*(\w+)\s*\]\s*:\s*([^\}]+?)\s*;?\s*\}
Replace: Record<$2, $3>
Depending on why you are doing this, using a std::set might be a better idea than std::vector.
It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.
This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.
A simpler version of your code would be:
dict(zip(names, d.values()))
If you want to keep the same structure, you can change it to:
vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}
(You can just as easily put list(d.values())
inside the comprehension instead of vlst
; it's just wasteful to do so since it would be re-generating the list every time).
This worked for me after struggling a bit
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
Sometimes, you just want to have a look at previous copies of files without the rigmarole of going through the diffs.
In such a case, it's just as easy to make a clone of a repository and checkout the specific commit that you are interested in and have a look at the subdirectory in that cloned repository. Because everything is local you can just delete this clone when you are done.
You should note that this is not necessarily the best design pattern. From the looks of it, you are essentially using your App Delegate to store what amounts to a global variable.
Matt Gallagher covered the issue of globals well in his Cocoa with Love article at http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html. In all likelyhood, your ClassA should be a singleton rather than a global in the AppDelegate, although its possible you intent ClassA to be more general purpose and not simply a singleton. In that case, you'd probably be better off with either a class method to return a pre-configured instance of Class A, something like:
+ (ClassA*) applicationClassA
{
static ClassA* appClassA = nil;
if ( !appClassA ) {
appClassA = [[ClassA alloc] init];
appClassA.downloadURL = @"http://www.abc.com/";
}
return appClassA;
}
Or alternatively (since that would add application specific stuff to what is possibly a general purpose class), create a new class whose sole purpose is to contain that class method.
The point is that application globals do not need to be part of the AppDelegate. Just because the AppDelegate is a known singleton, does not mean every other app global should be mixed in with it even if they have nothing conceptually to do with handling the NSApplication delegate methods.
split()
method in JavaScript is used to convert a string to an array.
It takes one optional argument, as a character, on which to split. In your case (~).
If splitOn is skipped, it will simply put string as it is on 0th position of an array.
If splitOn is just a “”, then it will convert array of single characters.
So in your case:
var arr = input.split('~');
will get the name at arr[0]
and the street at arr[1]
.
You can read for a more detailed explanation at Split on in JavaScript
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
You can convert that time in Unix timestamp by using
select UNIX_TIMESTAMP('2013-11-26 01:24:34')
then convert it in the readable format in whatever format you need
select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");
For in detail you can visit link
Never trust user data.
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The trim()
function removes whitespace and other predefined characters from both sides of a string.
The stripslashes()
function removes backslashes
The htmlspecialchars()
function converts some predefined characters to HTML entities.
The predefined characters are:
& (ampersand) becomes &
" (double quote) becomes "
' (single quote) becomes '
< (less than) becomes <
> (greater than) becomes >
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
I find that if I try things that others say do not work, it's how I learn the most.
<p> </p>
<p>README.txt</p>
<p> </p>
<div id="list">
<p><iframe src="README.txt" frameborder="0" height="400"
width="95%"></iframe></p>
</div>
This worked for me. I used the yellow background-color that I set in the stylesheet.
#list p {
font: arial;
font-size: 14px;
background-color: yellow ;
}
When want to get row size with size() function, below code can be used:
size(A,1)
Another usage for it:
[height, width] = size(A)
So, you can get 2 dimension of your matrix.
If you are using maven just do:
mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true
I use the readonly
attribute instead of disabled
attribute - as this will still submit the value when the field is readonly.
Note: Any presence of the readonly attribute will make the field readonly
even if set to false, so hence why I branch the editor for code like below.
@if (disabled)
{
@Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control", @readonly = "" } })
}
else
{
@Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
found here
You need to intent
your current context
to another activity first with startActivity
. After that you can finish
your current activity
from where you redirect.
Intent intent = new Intent(this, FirstActivity.class);// New activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
- Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.
I use a classical javascript to set value to hidden input
$scope.SetPersonValue = function (PersonValue)
{
document.getElementById('TypeOfPerson').value = PersonValue;
if (PersonValue != 'person')
{
document.getElementById('Discount').checked = false;
$scope.isCollapsed = true;
}
else
{
$scope.isCollapsed = false;
}
}
Check FlatStyle property. Setting it to "System" makes the checkbox sunken in my environment.
There are several file versions on the great Christoph Gohlke's site.
Something I have found important when installing wheels from this site is to first run this from the Python console:
import pip
print(pip.pep425tags.get_supported())
so that you know which version you should install for your computer. Picking the wrong version may fail the installing of the package (especially if you don't use the right CPython tag, for example, cp27).
You can use OR()
to group expressions (as well as AND()
):
=IF(OR(condition1, condition2), true, false)
=IF(AND(condition1, condition2), true, false)
So if you wanted to test for "cat" and "22":
=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")
bash -n scriptname
Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello
instead of echo hello
.
Just Follow This
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
1.Check your server status.
2.Check the port status.
For example 3306 netstat -nupl|grep 3306
.
3.Check your firewalls. For example add 3306
vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT
Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:
Gem::Specification.sort{|a,b| a.name <=> b.name}.map {|a| puts "#{a.name} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil
When you want to show an URL of remote branches, try:
git remote -v
Here it is in one line, without having to retype any of the variables or their values:
fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})
This worked for me. Running android API 19 and above.
FragmentManager fragMan = getFragmentManager();
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
Using DOM's getAttribute()
property
var brand = mydiv.getAttribute("data-myval")//returns "10"
mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20"
mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirely
Using JavaScript's dataset
property
var myval = mydiv.dataset.myval //returns "10"
mydiv.dataset.myval = '20' //changes "data-myval" to "20"
mydiv.dataset.myval = null //removes "data-myval" attribute
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
You can also return all selected checkboxes value in comma separated string. This will also make it easier for you when you send it as a parameter to SQL
Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string
And here is the javascript
function showSelectedValues()
{
alert($("input[name=chkboxName]:checked").map(function () {
return this.value;
}).get().join(","));
}
Here is the HTML sample
<html>
<head>
</head>
<body>
<div>
<input name="chkboxName" type="checkbox" value="one_name" checked>
<input name="chkboxName" type="checkbox" value="one_name1">
<input name="chkboxName" type="checkbox" value="one_name2">
</div>
</body>
</html>
One trick is to turn on the rewrite log. To turn it on, try this line in your apache main config or current virtual host file (not in .htaccess
):
LogLevel alert rewrite:trace6
Before Apache httpd 2.4 mod_rewrite, such a per-module logging configuration did not exist yet, instead you could use the following logging settings:
RewriteEngine On
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
Some might want certain class constants public while others private.
private keyword can be used to limit the scope of constants within the same swift file.
class MyClass {
struct Constants {
static let testStr = "test"
static let testStrLen = testStr.characters.count
//testInt will not be accessable by other classes in different swift files
private static let testInt = 1
}
func ownFunction()
{
var newInt = Constants.testInt + 1
print("Print testStr=\(Constants.testStr)")
}
}
Other classes will be able to access your class constants like below
class MyClass2
{
func accessOtherConstants()
{
print("MyClass's testStr=\(MyClass.Constants.testStr)")
}
}
For Windows, it is quite easy to stop/kill flask server -
It's possible using multiple handlers.
import logging
import auxiliary_module
# create logger with 'spam_application'
log = logging.getLogger('spam_application')
log.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
log.addHandler(ch)
log.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
log.info('created an instance of auxiliary_module.Auxiliary')
log.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
log.info('finished auxiliary_module.Auxiliary.do_something')
log.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
log.info('done with auxiliary_module.some_function()')
# remember to close the handlers
for handler in log.handlers:
handler.close()
log.removeFilter(handler)
Please see: https://docs.python.org/2/howto/logging-cookbook.html
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
In the selected answer, there is not check for marshmallow permission. It will not work directly in marshmallow 6.0 or above device.
I know I am too late but this question has large vote so I thought it will help to others in future.
In marshmallow devices we need to take run time permission for call...
Here is example to make call in marshmallow or above.
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
It is your setting as the owner of your local repo. Change it like this:
git remote set-head origin some_branch
And origin/HEAD will point to your branch instead of master. This would then apply to your repo only and not for others. By default, it will point to master, unless something else has been configured on the remote repo.
Manual entry for remote set-head provides some good information on this.
Edit: to emphasize: without you telling it to, the only way it would "move" would be a case like renaming the master branch, which I don't think is considered "organic". So, I would say organically it does not move.
You should look at the documentation for the Action method; it's explained well. For your case, this should work:
@Html.Action("GetOptions", new { pk="00", rk="00" });
The controllerName
parameter will default to the controller from which Html.Action
is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:
@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
This answer is meant to be a rather short and sweet one to answer (part of) the titled question. If you want an answer with more detail that explains why you have to put them there, please go here.
The general rule for putting the typename
keyword is mostly when you're using a template parameter and you want to access a nested typedef
or using-alias, for example:
template<typename T>
struct test {
using type = T; // no typename required
using underlying_type = typename T::type // typename required
};
Note that this also applies for meta functions or things that take generic template parameters too. However, if the template parameter provided is an explicit type then you don't have to specify typename
, for example:
template<typename T>
struct test {
// typename required
using type = typename std::conditional<true, const T&, T&&>::type;
// no typename required
using integer = std::conditional<true, int, float>::type;
};
The general rules for adding the template
qualifier are mostly similar except they typically involve templated member functions (static or otherwise) of a struct/class that is itself templated, for example:
Given this struct and function:
template<typename T>
struct test {
template<typename U>
void get() const {
std::cout << "get\n";
}
};
template<typename T>
void func(const test<T>& t) {
t.get<int>(); // error
}
Attempting to access t.get<int>()
from inside the function will result in an error:
main.cpp:13:11: error: expected primary-expression before 'int'
t.get<int>();
^
main.cpp:13:11: error: expected ';' before 'int'
Thus in this context you would need the template
keyword beforehand and call it like so:
t.template get<int>()
That way the compiler will parse this properly rather than t.get < int
.
Use the first:
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
It's explicit of what's going on - less chance of misreading rbegin
as begin
, even with a comment. It's clear and readable which is exactly what you want.
Also, the second one may be less efficient than the first given the nature of reverse iterators, although you would have to profile it to be sure.
In linux, I went to /var/opt/mssql/data/
folder and opened a terminal with sudo
then, changed my *.mdf and *.ldf file permissions as below in which you replace yourDB
with your Database file name and myUser
to currently logged username:
chmod 755 yourDB.mdf
chown myUser yourDB.mdf
chmod 755 yourDB.ldf
chown myUser yourDB.ldf
After that, it was reconnected without any issue.
This is kind of stupid, but I got this error message by accidentally using [formControl]
instead of [formGroup]
. See here:
WRONG
@Component({
selector: 'app-application-purpose',
template: `
<div [formControl]="formGroup"> <!-- '[formControl]' IS THE WRONG ATTRIBUTE -->
<input formControlName="formGroupProperty" />
</div>
`
})
export class MyComponent implements OnInit {
formGroup: FormGroup
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
formGroupProperty: ''
})
}
}
RIGHT
@Component({
selector: 'app-application-purpose',
template: `
<div [formGroup]="formGroup"> <!-- '[formGroup]' IS THE RIGHT ATTRIBUTE -->
<input formControlName="formGroupProperty" />
</div>
`
})
export class MyComponent implements OnInit {
formGroup: FormGroup
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
formGroupProperty: ''
})
}
}
You're looking for http_build_query()
.
Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?
If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:
Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish
....otherwise you can convert with a formula by using
=TEXT(A1,"0000-00-00")+0
and format in required date format
If you are using php-intl to localize your application, you probably want to use ResourceBundle::getLocales() instead of static list that you maintain yourself. It can also give you locales for particular language.
<?php
print_r(ResourceBundle::getLocales(''));
/* Output might show
* Array
* (
* [0] => af
* [1] => af_NA
* [2] => af_ZA
* [3] => am
* [4] => am_ET
* [5] => ar
* [6] => ar_AE
* [7] => ar_BH
* [8] => ar_DZ
* [9] => ar_EG
* [10] => ar_IQ
* ...
*/
?>
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
ALTER TABLE `user_customer_permission` MODIFY `id` INT;
ALTER TABLE `user_customer_permission` DROP PRIMARY KEY;
Although Marcelo's solution seems to be working great, you may not need to download the font at all! Just link to it remotely.
E.g the font is hosted on example.com, do
@font-face {
font-family: "Font Name";
font-style: normal;
src: url(http://example.com/webfonts/font-name.woff);
}
You may easily figure out the direct url to the font by looking into css code from example.com and see how they linked the file.
For US Phone Numbers
/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/
Let’s divide this regular expression in smaller fragments to make is easy to understand.
/^\(?
: Means that the phone number may begin with an optional (
.(\d{3})
: After the optional (
there must be 3 numeric digits. If the phone number does not have a (
, it must start with 3 digits. E.g. (308
or 308
.\)?
: Means that the phone number can have an optional )
after first 3 digits.[- ]?
: Next the phone number can have an optional hyphen (-
) after )
if present or after first 3 digits.(\d{3})
: Then there must be 3 more numeric digits. E.g (308)-135
or 308-135
or 308135
[- ]?
: After the second set of 3 digits the phone number can have another optional hyphen (-
). E.g (308)-135-
or 308-135-
or 308135-
(\d{4})$/
: Finally, the phone number must end with four digits. E.g (308)-135-7895
or 308-135-7895
or 308135-7895
or 3081357895
.
Reference :
The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int @int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"
Most of the time you would create a list in groovy rather than an array. You could do it like this:
names = ["lucas", "Fred", "Mary"]
Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:
names = "lucas Fred Mary".split()
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
#ck-button:hover {
background:red;
}
Fiddle: http://jsfiddle.net/zAFND/4/
You can use below command to see who have changed what in a file.
git blame <filename>
In Spring, bean scope is used to decide which type of bean instance should be returned from Spring container back to the caller.
5 types of bean scopes are supported :
Singleton : It returns a single bean instance per Spring IoC container.This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.If no bean scope is specified in bean configuration file, default to singleton.
Prototype : It returns a new bean instance each time when requested. It does not store any cache version like singleton.
Request : It returns a single bean instance per HTTP request.
Session : It returns a single bean instance per HTTP session (User level session).
GlobalSession : It returns a single bean instance per global HTTP session. It is only valid in the context of a web-aware Spring ApplicationContext (Application level session).
In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton.
Try this
df = pd.read_csv("rating-data.tsv",sep='\t')
df.head()
You actually need to fix the sep parameter.
You are allocating your string on the stack, and then returning a pointer to it. When your function returns, any stack allocations become invalid; the pointer now points to a region on the stack that is likely to be overwritten the next time a function is called.
In order to do what you're trying to do, you need to do one of the following:
malloc
or similar, then return that pointer. The caller will then need to call free
when it is done with the memory.There is a Rails inbuilt method called 'underscore' that you can use for this purpose
"CamelCaseString".underscore #=> "camel_case_string"
The 'underscore' method can typically be considered as inverse of 'camelize'
you can try this too And it will work:
DECLARE
a NUMBER;
b NUMBER;
BEGIN
a :=: a; --this will take input from user
b :=: b;
DBMS_OUTPUT.PUT_LINE('a = '|| a);
DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;
You're right using div.container-fluid
and you also need a div.row
child. Then, the content must be placed inside without any grid columns.
If you have a look at the docs you can find this text:
- Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
- Use rows to create horizontal groups of columns.
Not using grid columns it's ok as stated here:
- Content should be placed within columns, and only columns may be immediate children of rows.
And looking at this example, you can read this text:
Full width, single column: No grid classes are necessary for full-width elements.
Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.
In the newest versions (from the 3.5.1315.0 beta), you can use the MajorUpgrade element instead of using your own.
For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded):
<MajorUpgrade
AllowDowngrades="no" DowngradeErrorMessage="!(loc.NewerVersionInstalled)"
AllowSameVersionUpgrades="no"
/>
i fell into a case where clearing the entire array failed with dim/redim :
having 2 module-wide arrays, Private inside a userform,
One array is dynamic and uses a class module, the other is fixed and has a special type.
Option Explicit
Private Type Perso_Type
Nom As String
PV As Single 'Long 'max 1
Mana As Single 'Long
Classe1 As String
XP1 As Single
Classe2 As String
XP2 As Single
Classe3 As String
XP3 As Single
Classe4 As String
XP4 As Single
Buff(1 To 10) As IPicture 'Disp
BuffType(1 To 10) As String
Dances(1 To 10) As IPicture 'Disp
DancesType(1 To 10) As String
End Type
Private Data_Perso(1 To 9, 1 To 8) As Perso_Type
Dim ImgArray() As New ClsImage 'ClsImage is a Class module
And i have a sub declared as public to clear those arrays (and associated run-time created controls) from inside and outside the userform like this :
Public Sub EraseControlsCreatedAtRunTime()
Dim i As Long
On Error Resume Next
With Me.Controls 'removing all on run-time created controls of the Userform :
For i = .Count - 1 To 0 Step -1
.Remove i
Next i
End With
Err.Clear: On Error GoTo 0
Erase ImgArray, Data_Perso
'ReDim ImgArray() As ClsImage ' i tried this, no error but wouldn't work correctly
'ReDim Data_Perso(1 To 9, 1 To 8) As Perso_Type 'without the erase not working, with erase this line is not needed.
End Sub
note : this last sub was first called from outside (other form and class module) with Call FormName.SubName
but had to replace it with Application.Run FormName.SubName
, less errors, don't ask why...
You cannot do that, see this question's answers.
You may use std:vector
instead.
You'll need to use a different SimpleDateFormat
object for each different pattern. That said, you don't need that many different ones, thanks to this:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
So, you'll need these formats:
"M/y"
(that covers 9/09
, 9/2009
, and 09/2009
)"M/d/y"
(that covers 9/1/2009
)"M-d-y"
(that covers 9-1-2009
)So, my advice would be to write a method that works something like this (untested):
// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...
Date tryParse(String dateString)
{
for (String formatString : formatStrings)
{
try
{
return new SimpleDateFormat(formatString).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
If you look at the Android resources, the seek bar actually use images.
You have to make a drawable which is transparent on top and bottom for say 10px and the center 5px line is visible.
Refer attached image. You need to convert it into a NinePatch.
+1 Database
Forms in your app can even re-translate themselves on the fly if corrections are made to the database.
We used a system where all the controls were mapped in an XML file (one per form) to language resource IDs, but all the IDs were in the database.
Basically, instead of having each control hold the ID (implementing an interface, or using the tag property in VB6), we used the fact that in .NET, the control tree was easily discoverable through reflection. A process when the form loaded would build the XML file if it was missing. The XML file would map the controls to their resource IDs, so this simply needed to be filled in and mapped to the database. This meant that there was no need to change the compiled binary if something was not tagged, or if it needed to be split to another ID (some words in English which might be used as both nouns and verbs might need to translate to two different words in the dictionary and not be re-used, but you might not discover this during initial assignment of IDs). But the fact is that the whole translation process becomes completely independent of your binary (every form has to inherit from a base form which knows how to translate itself and all its controls).
The only ones where the app gets more involved is when a phase with insertion points is used.
The database translation software was your basic CRUD maintenance screen with various workflow options to facilitate going through the missing translations, etc.
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser
which is doing most of the work. Where he puts req.body.name
, I believe he/she is using body-parser
to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring
which is a built-in Node module. See the answers in the link below for an example of how to use querystring
.
It might help to look at this answer, which is very similar to your quest.
In my case I had into the manifest file an invalid tag structure, I had an opened activity closed but inside it where were ore activities (...)
which invalidates file correctness, to find it it took quite two hours, error reported missing/unknown <activity>
.
Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.
the controller
.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
function($route, $routeParams, $location) {
...
this.goToView = function(viewName){
$location.url('/' + viewName);
}
}]
);
the view
...
<li ng-click="general.goToView('Home')">HOME</li>
...
What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.
Thanks for the previous posts!
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
System.out.println("Enter a number (-1 to end):"+num);
int result=0;
int i=0;
while(true)
{
int n=num%10;
if(n==-1){
break;
}
i++;
System.out.println("Digit"+i+" = "+n);
result=result*10+n;
num=num/10;
if(num==0)
{
break;
}
}
}
}
if you use your website in the same network as the server IE likes to switch to compability mode despite DOCTYPE.
Adding meta http-equiv="X-UA-Compatible" content="IE=Edge"
disables this unwanted behaviour.
The easiest single-line solution is to use
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( "Your message here" ) };
For serialized JSON content:
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };
It is this line button2.Enabled == true
, it should be button2.Enabled = true
. You are doing comparison when you should be doing assignment.
It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Here's a link describing this:
All commands must be executed while connected to the right database in the right database cluster. Make sure of it.
The user needs access to the database, obviously:
GRANT CONNECT ON DATABASE my_db TO my_user;
And (at least) the USAGE
privilege on the schema:
GRANT USAGE ON SCHEMA public TO my_user;
Or grant USAGE
on all custom schemas:
DO
$$
BEGIN
-- RAISE NOTICE '%', ( -- use instead of EXECUTE to see generated commands
EXECUTE (
SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
FROM pg_namespace
WHERE nspname <> 'information_schema' -- exclude information schema and ...
AND nspname NOT LIKE 'pg\_%' -- ... system schemas
);
END
$$;
Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;
For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).
There are some other objects, the manual for GRANT
has the complete list as of Postgres 12:
privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)
But the rest is rarely needed. More details:
Consider upgrading to a current version.
The most elegant and flexible solution I have found so far is here: http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html
Basically, follow these steps:
Create custom view class, for your dropdown Adapter. In this custom class, you need to overwrite and set your custom dropdown item layout in getView() and getDropdownView() method. My code is as below:
public class CustomArrayAdapter extends ArrayAdapter<String>{
private List<String> objects;
private Context context;
public CustomArrayAdapter(Context context, int resourceId,
List<String> objects) {
super(context, resourceId, objects);
this.objects = objects;
this.context = context;
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View row=inflater.inflate(R.layout.spinner_item, parent, false);
TextView label=(TextView)row.findViewById(R.id.spItem);
label.setText(objects.get(position));
if (position == 0) {//Special style for dropdown header
label.setTextColor(context.getResources().getColor(R.color.text_hint_color));
}
return row;
}
}
In your activity or fragment, make use of the custom adapter for your spinner view. Something like this:
Spinner sp = (Spinner)findViewById(R.id.spMySpinner);
ArrayAdapter<String> myAdapter = new CustomArrayAdapter(this, R.layout.spinner_item, options);
sp.setAdapter(myAdapter);
where options is the list of dropdown item string.
Here I updated the sample code in Kotlin. Please note on Nougat and above version Uri.fromFile(file)
is not working and it crashes the app for that need to implement FileProvider which is safest way to send files from intent. For implementing this refer this answer or this article
private fun takePhotoFromCamera() {
val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
if (isDeviceSupportCamera) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
System.currentTimeMillis().toString() + ".jpg")
// fileUri = Uri.fromFile(file)
fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
}
} else {
Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
realPath = file?.path
//do what ever you want to do
}
}
}
Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate
getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.
$('.datepicker').datepicker("getDate")
or
$('.datepicker').datepicker("getDate").valueOf()
Even more concise:
data = data[:75]
If it is less than 75 characters there will be no change.
Use Diagrams
| Show Diagram...
from the context menu of a package. Invoking it on the project root will show module dependencies diagram.
If you need multiple packages, you can drag & drop them to the already opened diagram for the first package and press e to expand it.
Note: This feature is available in the Ultimate Edition, not the free Community Edition.
You can concat many kind of expression by sorrounding your simple/complex expression between ||
characters:
<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>
just for modifying certain property from object collection you could directly use forEach with a collection as follows
collection.forEach(c -> c.setXyz(c.getXyz + "a"))
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Here's Swift 3:
if let htmlFile = Bundle.main.path(forResource: "aa", ofType: "html"){
do{
let htmlString = try NSString(contentsOfFile: htmlFile, encoding:String.Encoding.utf8.rawValue )
messageWebView.loadHTMLString(htmlString as String, baseURL: nil)
}
catch _ {
}
}
$http is a promise too, you can make it simpler:
return $q.all(tasks.map(function(d){
return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
}));
I solved my issue by removing this code from .csproj
file:
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
in stead of
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Just for the record if somebody needs a way to handle signals on Windows. I had a requirement to handle from prog A calling prog B through os/exec but prog B never was able to terminate gracefully because sending signals through ex. cmd.Process.Signal(syscall.SIGTERM) or other signals are not supported on Windows. The way I handled is by creating a temp file as a signal ex. .signal.term through prog A and prog B needs to check if that file exists on interval base, if file exists it will exit the program and handle a cleanup if needed, I'm sure there are other ways but this did the job.
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
Here is my code:
html:
const upload = (file) => {_x000D_
console.log(file);_x000D_
_x000D_
_x000D_
_x000D_
fetch('http://localhost:8080/files/uploadFile', { _x000D_
method: 'POST',_x000D_
// headers: {_x000D_
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",_x000D_
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ? // multipart/form-data _x000D_
// },_x000D_
body: file // This is your file object_x000D_
}).then(_x000D_
response => response.json() // if the response is a JSON object_x000D_
).then(_x000D_
success => console.log(success) // Handle the success response object_x000D_
).catch(_x000D_
error => console.log(error) // Handle the error response object_x000D_
);_x000D_
_x000D_
//cvForm.submit();_x000D_
};_x000D_
_x000D_
const onSelectFile = () => upload(uploadCvInput.files[0]);_x000D_
_x000D_
uploadCvInput.addEventListener('change', onSelectFile, false);
_x000D_
<form id="cv_form" style="display: none;"_x000D_
enctype="multipart/form-data">_x000D_
<input id="uploadCV" type="file" name="file"/>_x000D_
<button type="submit" id="upload_btn">upload</button>_x000D_
</form>_x000D_
<ul class="dropdown-menu">_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>_x000D_
</ul>
_x000D_
Basic Generic Question - Simplest Generic Answer ;)
Given the information I will make the assumption that you might be trying a basic approach to coding, building/compiling and running a simple console app like "Hello World", using some simple text editor and some Command Shell.
This error occurs in the fallowing scenario:
..\SomePath>javac HelloWorld.java
..\SomePath>java HelloWorld.class
In other words, use:
..\SomePath>java HelloWorld
P.S. The adding the file extension .class produces the same mistake. Also be sure to have the Java's (JDK/JRE) bin folder in the operating system's Environment Variables's PATH.(Lookup for more details other posts on this) P.P.S Was I correct in my assumption/s?
The pattern yyyy-MM-dd
isn't an officially supported format for Date
constructor. Firefox seems to support it, but don't count on other browsers doing the same.
Here are some supported strings:
DateJS seems like a good library for parsing non standard date formats.
Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:
Date Time String Format
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:
- YYYY is the decimal digits of the year in the Gregorian calendar.
- "-" (hyphon) appears literally twice in the string.
- MM is the month of the year from 01 (January) to 12 (December).
- DD is the day of the month from 01 to 31.
- "T" appears literally in the string, to indicate the beginning of the time element.
- HH is the number of complete hours that have passed since midnight as two decimal digits.
- ":" (colon) appears literally twice in the string.
- mm is the number of complete minutes since the start of the hour as two decimal digits.
- ss is the number of complete seconds since the start of the minute as two decimal digits.
- "." (dot) appears literally in the string.
- sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the "." and the milliseconds field may be omitted.
- Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression hh:mm
This format includes date-only forms:
- YYYY
- YYYY-MM
- YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
- THH:mm
- THH:mm:ss
- THH:mm:ss.sss
Also included are "date-times" which may be any combination of the above.
So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.
Update: after looking at datejs documentation, using it, your problem should be solved using code like this:
var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
This is what I would do if passed a string buffer to fill and I knew the buffer was big enough (ie at least 16 characters long):
sprintf(buffer, "%d.%d.%d.%d",
(ip >> 24) & 0xFF,
(ip >> 16) & 0xFF,
(ip >> 8) & 0xFF,
(ip ) & 0xFF);
This would be slightly faster than creating a byte array first, and I think it is more readable. I would normally use snprintf, but IP addresses can't be more than 16 characters long including the terminating null.
Alternatively if I was asked for a function returning a char*:
char* IPAddressToString(int ip)
{
char[] result = new char[16];
sprintf(result, "%d.%d.%d.%d",
(ip >> 24) & 0xFF,
(ip >> 16) & 0xFF,
(ip >> 8) & 0xFF,
(ip ) & 0xFF);
return result;
}
Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.
Use of the functionality provided by the new
keyword has several advantages over building each object from scratch:
prototype
and use new
to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.And yes, new
has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:
function foo()
{
// if user accidentally omits the new keyword, this will
// silently correct the problem...
if ( !(this instanceof foo) )
return new foo();
// constructor logic follows...
}
Now you can have the advantages of new
without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:
if ( !(this instanceof arguments.callee) )
throw new Error("Constructor called as a function");
(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)
John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with
is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).
If you want the output to be
array([1.6e-01, 9.9e-01, 3.6e-04])
the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:
def my_round(value, N):
exponent = np.ceil(np.log10(value))
return 10**exponent*np.round(value*10**(-exponent), N)
For a general solution handling 0
and negative values as well, you can do something like this:
def my_round(value, N):
value = np.asarray(value).copy()
zero_mask = (value == 0)
value[zero_mask] = 1.0
sign_mask = (value < 0)
value[sign_mask] *= -1
exponent = np.ceil(np.log10(value))
result = 10**exponent*np.round(value*10**(-exponent), N)
result[sign_mask] *= -1
result[zero_mask] = 0.0
return result
You can use the Screen object to get this.
The following is an example of what it would return:
Screen {
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
pixelDepth: 24,
top: 414,
left: 1920,
availTop: 414,
availLeft: 1920
}
To get your screenWidth
variable, just use screen.width
, same with screenHeight
, you would just use screen.height
.
To get your window width and height, it would be screen.availWidth
or screen.availHeight
respectively.
For the pageX
and pageY
variables, use window.screenX or Y
. Note that this is from the VERY LEFT/TOP OF YOUR LEFT/TOP-est SCREEN. So if you have two screens of width 1920
then a window 500px from the left of the right screen would have an X value of 2420
(1920+500). screen.width/height
, however, display the CURRENT screen's width or height.
To get the width and height of your page, use jQuery's $(window).height()
or $(window).width()
.
Again using jQuery, use $("html").offset().top
and $("html").offset().left
for your pageX
and pageY
values.
The first one is useful when you need the index of the element as well. This is basically equivalent to the other two variants for ArrayList
s, but will be really slow if you use a LinkedList
.
The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate. But this has the disadvantage of being a little too verbose IMO.
The third version is my preferred choice as well. It is short and works for all cases where you do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the Collection
in any way - which is the most common case).
You can use the start (^
) and end ($
) of line indicators:
^[0-9]{2}$
Some language also have functions that allows you to match against an entire string, where-as you were using a find
function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^
and $
will be redundant.
It is easy to create a self-signed certificate, import it, and bind it to your website.
1.) Create a self-signed certificate:
Run the following 4 commands, one at a time, from an elevated Command Prompt:
cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64
makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.3 -sv localhost.pvk localhost.cer
cert2spc localhost.cer localhost.spc
pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx
2.) Import certificate to Trusted Root Certification Authorities store:
start --> run --> mmc.exe --> Certificates plugin --> "Trusted Root Certification Authorities" --> Certificates
Right-click Certificates --> All Tasks --> Import Find your "localhost" Certificate at C:\Program Files (x86)\Windows Kits\8.1\bin\x64\
3.) Bind certificate to website:
start --> (IIS) Manager --> Click on your Server --> Click on Sites --> Click on your top level site --> Bindings
Add or edit a binding for https and select the SSL certificate called "localhost".
4.) Import Certificate to Chrome:
Chrome Settings --> Manage Certificates --> Import .pfx certificate from C:\certificates\ folder
Test Certificate by opening Chrome and navigating to https://localhost/
Each version of Visual Studio prior to Visual Studio 2010 is tied to a specific .NET framework. (VS2008 is .NET 3.5, VS2005 is .NET 2.0, VS2003 is .NET1.1) Visual Studio 2010 and beyond allow for targeting of prior framework versions but cannot be used for future releases. You must use Visual Studio 2012 in order to utilize .NET 4.5.
For IntelliJ IDEA Ultimate latest version as of 18th Dec 2017, if the above suggestions don't work, then please try the following: Right Click on the project and navigate to "Open Module Settings". Open it, then change the "Language Level" from the dropdown.
First make a xml file with contents shown below and name it border.xml and place it inside the layout folder inside the res directory
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="#0000" />
<padding android:left="0dp" android:top="1dp" android:right="0dp"
android:bottom="1dp" />
</shape>
After that inside the code use
TextView tv = (TextView)findElementById(R.id.yourTextView);
tv.setBackgroundResource(R.layout.border);
This will make a black line on top and bottom of the TextView.
File.exist?("directory")
Dir[]
returns an array, so it will never be nil
. If you want to do it your way, you could do
Dir["directory"].empty?
which will return true
if it wasn't found.
purely CSS
input[type=search] {
min-width: 320px;
height: 24px;
border: 1px solid #E6E6E6;
border-radius: 8px;
margin-top: 6px;
background-image: url('/img/search.png');
background-size: 16px;
background-position: 280px;
background-repeat: no-repeat;
}
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
Try envsubst
FOO=foo
BAR=bar
export FOO BAR
envsubst <<EOF
FOO is $FOO
BAR is $BAR
EOF
Thanks to this thread (https://community.oracle.com/thread/473276)
select sys_context('userenv','service_name') from dual;
It can be executed with a regular user account, no need for sysdba rights
Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace
method with your Base64String and replace "image/png"
with "image/octet-stream"
:
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {_x000D_
const img = document.getElementById('embedImage');_x000D_
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
'9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
_x000D_
const button = document.getElementById('saveImage');_x000D_
button.addEventListener('click', () => {_x000D_
window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<img id="embedImage" alt="Red dot" />_x000D_
<button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).
The command line option
-verbose:gc
causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:[GC 325407K->83000K(776768K), 0.2300771 secs] [GC 325816K->83372K(776768K), 0.2454258 secs] [Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g.,
325407K->83000K
from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.The next number in parentheses (e.g.,
(776768K)
again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.The last item on the line (e.g.,
0.2300771 secs
) indicates the time taken to perform the collection; in this case approximately a quarter of a second.The format for the major collection in the third line is similar.
The format of the output produced by
-verbose:gc
is subject to change in future releases.
I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display
, or changing dimensions and setting to overflow:hidden
) in order to correctly hide the element and prevent it from taking up visible space.
Therefore, create an animation for the elements in question, and simply toggle visibility:hidden;
after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.
CSS
html, body {
height:100%;
width:100%;
margin:0;
padding:0;
}
#hideMe {
-moz-animation: cssAnimation 0s ease-in 5s forwards;
/* Firefox */
-webkit-animation: cssAnimation 0s ease-in 5s forwards;
/* Safari and Chrome */
-o-animation: cssAnimation 0s ease-in 5s forwards;
/* Opera */
animation: cssAnimation 0s ease-in 5s forwards;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
}
@keyframes cssAnimation {
to {
width:0;
height:0;
overflow:hidden;
}
}
@-webkit-keyframes cssAnimation {
to {
width:0;
height:0;
visibility:hidden;
}
}
HTML
<div id='hideMe'>Wait for it...</div>
Got a similar error after running npm-check-updates -u
. Solved it by removing node_modules
folder and package-lock.json
. After that a new npm install
and everything worked.
My exception:
Failed to load parser '@typescript-eslint/parser' declared in 'package.json » eslint-config-react-app#overrides[0]': Cannot find module '@typescript-eslint/parser'
This is a very generic question and there is a lot of ways it can be answered.
If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single "production" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.
In your specific example, you could for example test the following:
To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).
Example testcase class in your case (without the methods contents defined):
import static org.junit.Assert.*;
public class AdditionTests {
@Test
public void testSimpleAddition() { ... }
@Test
public void testPositiveNegativeAddition() { ... }
@Test
public void testNegativePositiveAddition() { ... }
@Test
public void testNegativeAddition() { ... }
@Test
public void testOverflow() { ... }
}
If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate "visually" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.
Simple Solution,worked for me
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
You can use the following construction:
var arr = [1,2,3,4,5,6,7,8,9,0,5];
var duplicate = arr.filter(function(item, i, arr) {
return -1 !== arr.indexOf(item, i + 1);
})
String key= "services_servicename"
ArrayList<String> data;
for(int i = 0; i lessthen data.size(); i++) {
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
servicesNameHashmap.put(key,data.get(i).getServiceName());
mServiceNameArray.add(i,servicesNameHashmap);
}
I have got the Best Results.
You just have to create new HashMap
like
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
in your for
loop. It will have same effect like same key and multiple values.
In the package import org.apache.commons.lang.SerializationUtils;
there is a method:
SerializationUtils.clone(Object);
Example:
this.myObjectCloned = SerializationUtils.clone(this.object);
There is a difference between them, continue
skips the loop's current iteration and executes the next iteration.pass
does nothing. It’s an empty statement placeholder.
I would rather give you an example, which will clarify this more better.
>>> for element in some_list:
... if element == 1:
... print "Pass executed"
... pass
... print element
...
0
Pass executed
1
2
>>> for element in some_list:
... if element == 1:
... print "Continue executed"
... continue
... print element
...
0
Continue executed
2
check it: Android Studio->file->project structure->app->flavors->min sdk version and if you want to run your application on your mobile you have to set min sdk version less than your device sdk(API) you can install any API levels.
There is maybe a bit of a gotcha in the phrasing of the original question:
I need to check that two conditions are both true before enabling a button
The first thing to remember that the ng-disabled directive is evaluating a condition under which the button should be, well, disabled, but the original question is referring to the conditions under which it should en enabled. It will be enabled under any circumstances where the ng-disabled expression is not "truthy".
So, the first consideration is how to rephrase the logic of the question to be closer to the logical requirements of ng-disabled. The logical inverse of checking that two conditions are true in order to enable a button is that if either condition is false then the button should be disabled.
Thus, in the case of the original question, the pseudo-expression for ng-disabled is "disable the button if condition1 is false or condition2 is false". Translating into the Javascript-like code snippet required by Angular (https://docs.angularjs.org/guide/expression), we get:
!condition1 || !condition2
Zoomlar has it right!
Look at the following:
echo "ls -l" | at 07:00
This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:
http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html
Hope it helps!
Combining some of the previous answers, this is the seedable random function you are looking for:
Math.seed = function(s) {
var mask = 0xffffffff;
var m_w = (123456789 + s) & mask;
var m_z = (987654321 - s) & mask;
return function() {
m_z = (36969 * (m_z & 65535) + (m_z >>> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >>> 16)) & mask;
var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
result /= 4294967296;
return result;
}
}
var myRandomFunction = Math.seed(1234);
var randomNumber = myRandomFunction();
You may need to install Hotfix KB980368.
This article describes a update that enables certain Internet Information Services (IIS) 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period. Specifically, these handlers are mapped to "." request paths. Currently, a handler that is mapped to a "." request path handles only requests whose URLs end with a period. For example, the handler handles only requests whose URLs resemble the following URL:
http://www.example.com/ExampleSite/ExampleFile.
After you apply this update, handlers that are mapped to a "*." request path can handle requests whose URLs end with a period and requests whose URLs do not end with a period. For example, the handler can now handle requests that resemble the following URLs:
http://www.example.com/ExampleSite/ExampleFile
http://www.example.com/ExampleSite/ExampleFile.
After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.
Simplified version:
Date.prototype.clone = function () {
return new Date(this.getTime());
}
You can use this:
Js:
function refreshFrame(){
$('#myFrame').attr('src', "http://blablab.com?v=");
}
Html:
`<iframe id="myFrame" src=""></iframe>`
JS Fiddle : https://jsfiddle.net/wpb20vzx/
Use for
instead of foreach
. foreach
doesn't expose its inner workings, it enumerates anything that is IEnumerable
(which doesn't have to have an index at all).
for (int i=0; i<arr.Length; i++)
{
...
}
Besides, if what you're trying to do is find the index of a particular item in the list, you don't have to iterate it at all by yourself. Use Array.IndexOf(item)
instead.
Look for an open listener on port 1433 (the default port). If you get any response after creating a tcp connection there, the server's probably up.
In case you want to have a separator in the name between levels, this function works well.
def flattenHierarchicalCol(col,sep = '_'):
if not type(col) is tuple:
return col
else:
new_col = ''
for leveli,level in enumerate(col):
if not level == '':
if not leveli == 0:
new_col += sep
new_col += level
return new_col
df.columns = df.columns.map(flattenHierarchicalCol)
This is how to set an image into ImageView
using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
Given that you're only converting to int
s to then perform a comparison, I'd just switch the table definition around to using varchar
also:
Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
and remove all of the attempted CONVERT
s from the rest of the query.
SELECT a.name, a.value AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on a.value = #myTempTable.num
GROUP BY a.name, a.value ORDER BY a.name
Once you started the Emulator from one shell, login to another shell & type
adb shell
You should see # prompt
displayed, this is your device(emulator) shell. Now , type following command at adb shell.
mount -o remount rw /sdcard
This will now remount /sdcard
with rw(read-write)
permission & now you can push your files into /sdcard
by using following command from your host shell.
`adb push filename.mp3 /sdcard,`
where filename.mp3 could be any file that you want to push into Android Emulator.
Hope this helps :)
following for different plateform
WINDOWS: Ctrl + F12
LINUX: Ctrl + F12
MAC OS X: control + F12 (or fn + control + F12, depending on your keyboard configuration)
In addition to the generic device (or "Any iOS Device" in newer versions of Xcode) mentioned in the other answers, it is possible that the "Archive" action is not selected for the current target in the scheme.
To view and edit at the current scheme, select Product > Schemes > Edit Scheme...
(Cmd+<), then make sure that the "Archive" action is checked in the line corresponding to the desired target.
In the image below, Archive
is not checked and the Archive
action is greyed out in the Product
menu. Checking the indicated checkbox fixed the issue for me.
I was getting the same fav icon error - 404 (Not Found). I used the following element in the <head>
element of my index.html file and it fixed the error:
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
You can try also:
document.body.offsetHeight
document.body.offsetWidth
In xcode 4.2
Goto, Product -> edit scheme -> click Run yourappname.app -> Diagonostics -> Enable Zombie object.
An element with ‘display: block’ (as div is by default) has a width determined by the width of its container. You can't make a block's width dependent on the width of its contents (shrink-to-fit).
(Except for blocks that are ‘float: left/right’ in CSS 2.1, but that's no use for centering.)
You could set the ‘display’ property to ‘inline-block’ to turn a block into a shrink-to-fit object that can be controlled by its parent's text-align property, but browser support is spotty. You can mostly get away with it by using hacks (eg. see -moz-inline-stack) if you want to go that way.
The other way to go is tables. This can be necessary when you have columns whose width really can't be known in advance. I can't really tell what you're trying to do from the example code — there's nothing obvious in there that would need a shrink-to-fit block — but a list of products could possibly be considered tabular.
[PS. never use ‘pt’ for font sizes on the web. ‘px’ is more reliable if you really need fixed size text, otherwise relative units like ‘%’ are better. And “clear: ccc both” — a typo?]
.center{
text-align:center;
}
.center > div{ /* N.B. child combinators don't work in IE6 or less */
display:inline-block;
}
There is an API called SMSLib, it's really awesome. http://smslib.org/
Now you have a lot of Saas providers that can give you this service using their APIs
Ex: mailchimp, esendex, Twilio, ...
Like that:
class Zoo {
AnimalClass: typeof Animal;
constructor(AnimalClass: typeof Animal ) {
this.AnimalClass = AnimalClass
let Hector = new AnimalClass();
}
}
Or just:
class Zoo {
constructor(public AnimalClass: typeof Animal ) {
let Hector = new AnimalClass();
}
}
typeof Class
is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.
Here's the relevant part of TypeScript docs. Search for the typeof
. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.
Updated package.json:
"build": {
"appId": "com.my-website.my-app",
"productName": "MyApp",
"copyright": "Copyright © 2019 ${author}",
"mac": {
"icon": "./public/icons/mac/icon.icns", <---------- set Mac Icons
"category": "public.app-category.utilities"
},
"win": {
"icon": "./public/icons/png/256x256.png" <---------- set Win Icon
},
"files": [
"./build/**/*",
"./dist/**/*",
"./node_modules/**/*",
"./public/**/*", <---------- need for get access to icons
"*.js"
],
"directories": {
"buildResources": "public" <---------- folder where placed icons
}
},
After build application you can see icons. This solution don't show icons in developer mode.
I don't setup icons in new BrowserWindow()
.
Slide up/down with alpha animation with a few note
slide_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@integer/activity_transition_time"
>
<translate
android:fromYDelta="100%p"
android:toYDelta="0"/>
<alpha
android:fromAlpha="0.5"
android:toAlpha="1"/>
</set>
slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@integer/activity_transition_time"
>
<translate
android:fromYDelta="0"
android:toYDelta="100%p"/>
<alpha
android:fromAlpha="1"
android:toAlpha="0.5"/>
</set>
no_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@integer/activity_transition_time"
android:fromYDelta="0"
android:toYDelta="0"/>
First Activity
startActivity(new Intent(this, SecondActivity.class));
overridePendingTransition(R.anim.slide_up, R.anim.no_animation); // remember to put it after startActivity, if you put it to above, animation will not working
// document say if we don't want animation we can put 0. However, if we put 0 instead of R.anim.no_animation, the exist activity will become black when animate
Second Activity
finish();
overridePendingTransition(R.anim.no_animation, R.anim.slide_down);
Done
MORE
I try to make the slide animation like iOS animation when present a View Model (like this https://www.youtube.com/watch?v=deZobvh2064) but failed.
Looking at iOS present animation you will see: The animation from bottom with alpha (about 50%) then it go very fast then slower, the animation time is about > 500ms (I use trim video tools for count the animation time https://www.kapwing.com/trim-video so it can not exactly 100%)
Then I try to apply to android.
To make alpha I use <alpha>
and success.
To make animation start faster than slower I use android:interpolator="a decelerate interpolator"
but it almost failed.
There are 3 default decelerate interpolator
in Android
@android:interpolator/decelerate_quad
-> factor = 1
@android:interpolator/decelerate_cubic
-> factor = 1.5
@android:interpolator/decelerate_quint
_> factor = 2.5
(higher factor <=> animation start more faster from start and more slower at end)
Here is a good tutorial http://cogitolearning.co.uk/2013/10/android-animations-tutorial-5-more-on-interpolators/ for understand it
I tried 3 above I can not achieve like iOS, the animation can not start faster like iOS. Then I create a custom decelerateInterpolator wiht factor = 3 like
<?xml version="1.0" encoding="utf-8"?>
<decelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:factor="3" />
and I increase the duration time from 500 -> 750
. It working well (very similar to iOS). However, it only working well in some device, in some device the animation is quite slow. Later on, I know that animation may different on different device (eg: some device will faster and some device will slower) so I can not make it the animation similar in all Android device. Therefore I don't use interpolator
. I don't know if my testing is exactly 100% or not but I hope this experience help
Assuming t1 is the folder with files in it, and t2 is the empty directory. What you want is something like this:
sudo cp -R t1/* t2/
Bear in mind, for the first example, t1 and t2 have to be the full paths, or relative paths (based on where you are). If you want, you can navigate to the empty folder (t2) and do this:
sudo cp -R t1/* ./
Or you can navigate to the folder with files (t1) and do this:
sudo cp -R ./* t2/
Note: The * sign (or wildcard) stands for all files and folders. The -R flag means recursively (everything inside everything).
Building on the accepted answer.
If the Object has properties you want to call say .properties() try!
var keys = Object.keys(myJSONObject);
for (var j=0; j < keys.length; j++) {
Object[keys[j]].properties();
}
Create a .htaccess file in directory and add this code to .htaccess file
AddHandler x-httpd-php .html .htm
or
AddType application/x-httpd-php .html .htm
It will force Apache server to parse HTML or HTM files as PHP Script
http://jsfiddle.net/LRD5x/30/ A simple solution.
HTML
<form ng-submit="sendForm($event)" ng-class={submitted:submitted}>
JS
$scope.sendForm = function($event) {
$event.preventDefault()
$scope.submitted = true
};
CSS
.submitted input.ng-invalid:not(:focus) {
background-color: #FA787E;
}
input.ng-invalid ~ .alert{
display:none;
}
.submitted input.ng-invalid ~ .alert{
display:block;
}
Though this is an old question, there's still one problem that I don't see anybody having addressed at all: garbage collection is almost impossible to specify.
In particular, the C++ standard is quite careful to specify the language in terms of externally observable behavior, rather than how the implementation achieves that behavior. In the case of garbage collection, however, there is virtually no externally observable behavior.
The general idea of garbage collection is that it should make a reasonable attempt at assuring that a memory allocation will succeed. Unfortunately, it's essentially impossible to guarantee that any memory allocation will succeed, even if you do have a garbage collector in operation. This is true to some extent in any case, but particularly so in the case of C++, because it's (probably) not possible to use a copying collector (or anything similar) that moves objects in memory during a collection cycle.
If you can't move objects, you can't create a single, contiguous memory space from which to do your allocations -- and that means your heap (or free store, or whatever you prefer to call it) can, and probably will, become fragmented over time. This, in turn, can prevent an allocation from succeeding, even when there's more memory free than the amount being requested.
While it might be possible to come up with some guarantee that says (in essence) that if you repeat exactly the same pattern of allocation repeatedly, and it succeeded the first time, it will continue to succeed on subsequent iterations, provided that the allocated memory became inaccessible between iterations. That's such a weak guarantee it's essentially useless, but I can't see any reasonable hope of strengthening it.
Even so, it's stronger than what has been proposed for C++. The previous proposal [warning: PDF] (that got dropped) didn't guarantee anything at all. In 28 pages of proposal, what you got in the way of externally observable behavior was a single (non-normative) note saying:
[ Note: For garbage collected programs, a high quality hosted implementation should attempt to maximize the amount of unreachable memory it reclaims. —end note ]
At least for me, this raises a serious question about return on investment. We're going to break existing code (nobody's sure exactly how much, but definitely quite a bit), place new requirements on implementations and new restrictions on code, and what we get in return is quite possibly nothing at all?
Even at best, what we get are programs that, based on testing with Java, will probably require around six times as much memory to run at the same speed they do now. Worse, garbage collection was part of Java from the beginning -- C++ places enough more restrictions on the garbage collector that it will almost certainly have an even worse cost/benefit ratio (even if we go beyond what the proposal guaranteed and assume there would be some benefit).
I'd summarize the situation mathematically: this a complex situation. As any mathematician knows, a complex number has two parts: real and imaginary. It appears to me that what we have here are costs that are real, but benefits that are (at least mostly) imaginary.
If we need to move from one component to another service then we have to define that service into app.module providers array.
array.length
isn't necessarily the number of items in the array:
var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101
The length of the array is one more than the highest index.
As stated before Array.size()
is not a valid method.
Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.
Example: http://jsfiddle.net/SHLu4/2/
It'll be something like:
<div class="container drop-shadow">
<div class="container">
<div class="row">
<div class="col-md-8">Main Area</div>
<div class="col-md-4">Side Area</div>
</div>
</div>
</div>
And your CSS:
<style>
.drop-shadow {
-webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
}
.container.drop-shadow {
padding-left:0;
padding-right:0;
}
</style>
NULL
is a value that is valid for any pointer type. It represents the absence of a value.
A void pointer is a type. Any pointer type is convertible to a void pointer hence it can point to any value. This makes it good for general storage but bad for use. By itself it cannot be used to access a value. The program must have extra context to understand the type of value the void pointer refers to before it can access the value.
Maybe I'm being dumb, but isn't table the obvious solution here?
<div class="parent">
<div class="fixed">
<div class="stretchToFit">
</div>
.parent{ display: table; width 100%; }
.fixed { display: table-cell; width: 150px; }
.stretchToFit{ display: table-cell; vertical-align: top}
Another way that I've figured out in chrome is even simpler, but man is it a hack!
.fixed{
float: left
}
.stretchToFit{
display: table-cell;
width: 1%;
}
This alone should fill the rest of the line horizontally, as table-cells do. However, you get some strange issues with it going over 100% of its parent, setting the width to a percent value fixes it though.
The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.
This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.
Another Solution to isolate a character in a string
package main
import "fmt"
func main() {
var word string = "ZbjTS"
// P R I N T
fmt.Println(word)
yo := string([]rune(word)[0])
fmt.Println(yo)
//I N D E X
x :=0
for x < len(word){
yo := string([]rune(word)[x])
fmt.Println(yo)
x+=1
}
}
for string arrays also:
fmt.Println(string([]rune(sArray[0])[0]))
// = commented line
Just clarifying what worked for me after much pain in linux (ubuntu based) on permission denied errors, and leveraging from Bert's answer above, I now use ...
$ pip install --user <package-name>
or if running pip on a requirements file ...
$ pip install --user -r requirements.txt
and these work reliably for every pip install including creating virtual environments.
However, the cleanest solution in my further experience has been to install python-virtualenv
and virtualenvwrapper
with sudo apt-get install
at the system level.
Then, inside virtual environments, use pip install
without the --user
flag AND without sudo
. Much cleaner, safer, and easier overall.
I had similar issue on MacBook Pro, I just followed the below link and issue got resolved. https://projectlombok.org/setup/eclipse
Steps followed:-
You have to walk the objects using reflection. Be careful as you do:
byte
is theoretically 1 byte doesn't mean it takes just one in memory.HashMap
or somesuch using object-equals as the comparator to eliminate infinite loops.@jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods.
You must get it via compatible way, others are deprecated:
Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);
Common immutable type:
int()
, float()
, complex()
str()
, tuple()
, frozenset()
, bytes()
Common mutable type (almost everything else):
list()
, bytearray()
set()
dict()
One trick to quickly test if a type is mutable or not, is to use id()
built-in function.
Examples, using on integer,
>>> i = 1
>>> id(i)
***704
>>> i += 1
>>> i
2
>>> id(i)
***736 (different from ***704)
using on list,
>>> a = [1]
>>> id(a)
***416
>>> a.append(2)
>>> a
[1, 2]
>>> id(a)
***416 (same with the above id)
brew install mysql
added mysql to /usr/local/Cellar/...
, so I needed to add :/usr/local/Cellar/
to my $PATH
and then which mysql_config
worked!
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
You can use the methods of the File class: http://docs.oracle.com/javase/7/docs/api/java/io/File.html
Try Using DateTime::createFromFormat
$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');
Output
2012-04-24
EDIT:
If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.
$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
OUTPUT:
2010-4-5
I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer
My problem was when converting .p12 certificate to .pem. I used:
openssl pkcs12 -in cert.p12 -out cert.pem
This converts and exports all certificates (CA + CLIENT) together with a private key into one file.
The problem was when I tried to verify if the hashes of certificate and key are matching by running:
// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5
// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5
This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/
I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.
So the solution was to export only CLIENT certificate together with private key:
openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``
Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5
HASHES MATCHED !!!
So I was able to make a curl request by running
curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com
without problems!!!
That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:
curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com
VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.
Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.
CollectionUtils.isEmpty(list))
In case anyone was wondering - it was probably my css...
@font-face
font-family: "bingo"
src: url('bingo.eot')
src: local('bingo')
src: url('bingo.svg#bingo') format('svg')
src: url('bingo.otf') format('opentype')
will render as
@font-face {
font-family: "bingo";
src: url('bingo.eot');
src: local('bingo');
src: url('bingo.svg#bingo') format('svg');
src: url('bingo.otf') format('opentype'); }
which seems to be close enough... just need to check the SVG rendering
Note that jQuery().css()
doesn't change stylesheet rules, it just changes the style of each matched element.
Instead, here's a javascript function I wrote to modify the stylesheet rules themselves.
/**
* Modify an existing stylesheet.
* - sheetId - the id of the <link> or <style> element that defines the stylesheet to be changed
* - selector - the id/class/element part of the rule. e.g. "div", ".sectionTitle", "#chapter2"
* - property - the CSS attribute to be changed. e.g. "border", "font-size"
* - value - the new value for the CSS attribute. e.g. "2px solid blue", "14px"
*/
function changeCSS(sheetId, selector, property, value){
var s = document.getElementById(sheetId).sheet;
var rules = s.cssRules || s.rules;
for(var i = rules.length - 1, found = false; i >= 0 && !found; i--){
var r = rules[i];
if(r.selectorText == selector){
r.style.setProperty(property, value);
found = true;
}
}
if(!found){
s.insertRule(selector + '{' + property + ':' + value + ';}', rules.length);
}
}
Advantages:
<head>
script before the DOM elements are created and therefore prior to the first rendering of the document, avoiding a visually-annoying render, then compute, then re-render. With jQuery, you'd have to wait for the DOM elements to be created, then re-style and re-render them.jQuery(newElement).css()
Caveats:
s.cssRules
defined, so they will fall back to s.rules
which has some peculiarities, such as odd/buggy behavior related to comma-delimited selectors, like "body, p"
. If you avoid those, you might be ok in older IE versions without modification, but I haven't tested it yet."first, second"
i.e the delimiter is a comma followed by a space character.!important
modifier without too much trouble.If you feel like making some improvements to this function, you'll find some useful API docs here: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet
Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution
echo 'xxx yyy zzze ' | grep -oE 'yyy'
There is also another possibilty. I load OpenGl shaders from resources like this:
static private String vertexShaderCode;
static private String fragmentShaderCode;
static {
vertexShaderCode = readResourceAsString("/res/raw/vertex_shader.glsl");
fragmentShaderCode = readResourceAsString("/res/raw/fragment_shader.glsl");
}
private static String readResourceAsString(String path) {
Exception innerException;
Class<? extends FloorPlanRenderer> aClass = FloorPlanRenderer.class;
InputStream inputStream = aClass.getResourceAsStream(path);
byte[] bytes;
try {
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return new String(bytes);
} catch (IOException e) {
e.printStackTrace();
innerException = e;
}
throw new RuntimeException("Cannot load shader code from resources.", innerException);
}
As you can see, you can access any resource in path /res/...
Change aClass
to your class. This also how I load resources in tests (androidTests)
Check for package-lock.json file at C:\Windows\system32
.
If it doesn't exist, run cmd
as admin and execute the following commands:
Set EXPO_DEBUG=true
npm config set package-lock false
npm install
Use two minipages.
\begin{minipage}[position]{width}
text
\end{minipage}