You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>()
. Try this:
@model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
@Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
</div>
</div>
This code will return the absolute path to the main script.
import os
def whereAmI():
return os.path.dirname(os.path.realpath(__import__("__main__").__file__))
This will work even in a module.
What you want is a type of software called a "Disassembler".
Quick google yields this: Link
I changed to open() from fopen() for my application, because fopen was causing double reads every time I ran fopen fgetc . Double reads were disruptive of what I was trying to accomplish. open() just seems to do what you ask of it.
sudo apt-get install php-mbstring
# if your are using php 7.1
sudo apt-get install php7.1-mbstring
# if your are using php 7.2
sudo apt-get install php7.2-mbstring
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
$scope.class = "red";_x000D_
$scope.changeClass = function(){_x000D_
if ($scope.class === "red")_x000D_
$scope.class = "blue";_x000D_
else_x000D_
$scope.class = "red";_x000D_
};_x000D_
});
_x000D_
.red{_x000D_
color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
<div ng-class="class">{{class}}</div>_x000D_
<button ng-click="changeClass()">Change Class</button> _x000D_
</body>
_x000D_
Here is the example working on jsFiddle
n is an int (immutable), and a copy is passed to the function, so in the function you are changing the copy.
X is a list (mutable), and a copy of the pointer is passed o the function so x.append(4) changes the contents of the list. However, you you said x = [0,1,2,3,4] in your function, you would not change the contents of x in main().
If you are using java-8 there's also another way to do this.
int[] arr = list.stream().mapToInt(i -> i).toArray();
What it does is:
Stream<Integer>
from the listIntStream
by mapping each element to itself (identity function), unboxing the int
value hold by each Integer
object (done automatically since Java 5)int
by calling toArray
You could also explicitly call intValue
via a method reference, i.e:
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
It's also worth mentioning that you could get a NullPointerException
if you have any null
reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:
//.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();
Example:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]
list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]
You can use tee
to write the result of your query to a file:
tee somepath\filename.txt
Try doing a "set | grep -i ssh" from the Git Bash prompt
If your setup is like mine you probably have these set:
GIT_SSH='C:\Program Files (x86)\PuTTY\plink.exe'
PLINK_PROTOCOL=ssh
SVN_SSH='"C:\\Program Files (x86)\\PuTTY\\plink.exe"'
I did a
unset GIT_SSH
unset PLINK_PROTOCOL
unset GIT_SVN
and it worked after that,.. I guess putty saves its keys somewhere else as $HOME/.ssh or something... (I've also had a problem on a box where $HOME was set to "C:\Users\usrnam" instead of "/C/Users/usrnam/"
anyway, your mileage may vary, but that fixed it for me. :-)
(probably just doing the unset GIT_SSH is enough, but I was on a roll)
Note: if unset doesn't work for you, try this:
set GIT_SSH=
You can make nginx ignore client aborts using:
location / {
proxy_ignore_client_abort on;
}
Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):
>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n Garply\n \n"
>>> print a
Foo
Bar
Baz
Garply
>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
Garply
>>>
Just found another solutions worked for me. You can use '\' sign before your one special.
passwd=\@31\&3*J
You probably have allProviders
typed as object[]
as well. And property country
does not exist on object
. If you don't care about typing, you can declare both allProviders
and countryProviders
as Array<any>
:
let countryProviders: Array<any>;
let allProviders: Array<any>;
If you do want static type checking. You can create an interface for the structure and use it:
interface Provider {
region: string,
country: string,
locale: string,
company: string
}
let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;
Using this Function u can define your won position
setBounds(500, 200, 647, 418);
Judging from your output it looks like you have defined START_DATE as a timestamp. If it were a regular date Oracle would be able to handle the implicit conversion. But as it isn't you need to explicitly cast those strings to be dates.
SQL> alter session set nls_date_format = 'dd-mon-yyyy hh24:mi:ss'
2 /
Session altered.
SQL>
SQL> select * from t23
2 where start_date between '15-JAN-10' and '17-JAN-10'
3 /
no rows selected
SQL> select * from t23
2 where start_date between to_date('15-JAN-10') and to_date('17-JAN-10')
3 /
WIDGET START_DATE
------------------------------ ----------------------
Small Widget 15-JAN-10 04.25.32.000
SQL>
But we still only get one row. This is because START_DATE has a time element. If we don't specify the time component Oracle defaults it to midnight. That is fine for the from side of the BETWEEN
but not for the until side:
SQL> select * from t23
2 where start_date between to_date('15-JAN-10')
3 and to_date('17-JAN-10 23:59:59')
4 /
WIDGET START_DATE
------------------------------ ----------------------
Small Widget 15-JAN-10 04.25.32.000
Product 1 17-JAN-10 04.31.32.000
SQL>
edit
If you cannot pass in the time component there are a couple of choices. One is to change the WHERE clause to remove the time element from the criteria:
where trunc(start_date) between to_date('15-JAN-10')
and to_date('17-JAN-10')
This might have an impact on performance, because it disqualifies any b-tree index on START_DATE. You would need to build a function-based index instead.
Alternatively you could add the time element to the date in your code:
where start_date between to_date('15-JAN-10')
and to_date('17-JAN-10') + (86399/86400)
Because of these problems many people prefer to avoid the use of between
by checking for date boundaries like this:
where start_date >= to_date('15-JAN-10')
and start_date < to_date('18-JAN-10')
For me, upgrading eslint-plugin-react to the latest version 7.21.5 fixed this
This article explains all the details http://kunststube.net/encoding/
WRITING TO BUFFER
if you write to a 4 byte buffer, symbol ?
with UTF8 encoding, your binary will look like this:
00000000 11100011 10000001 10000010
if you write to a 4 byte buffer, symbol ?
with UTF16 encoding, your binary will look like this:
00000000 00000000 00110000 01000010
As you can see, depending on what language you would use in your content this will effect your memory accordingly.
e.g. For this particular symbol: ?
UTF16 encoding is more efficient since we have 2 spare bytes to use for the next symbol. But it doesn't mean that you must use UTF16 for Japan alphabet.
READING FROM BUFFER
Now if you want to read the above bytes, you have to know in what encoding it was written to and decode it back correctly.
e.g. If you decode this :
00000000 11100011 10000001 10000010
into UTF16 encoding, you will end up with ?
not ?
Note: Encoding and Unicode are two different things. Unicode is the big (table) with each symbol mapped to a unique code point. e.g. ?
symbol (letter) has a (code point): 30 42 (hex). Encoding on the other hand, is an algorithm that converts symbols to more appropriate way, when storing to hardware.
30 42 (hex) - > UTF8 encoding - > E3 81 82 (hex), which is above result in binary.
30 42 (hex) - > UTF16 encoding - > 30 42 (hex), which is above result in binary.
I had similar issue with <input type="range" />
and I solved it with
-webkit-tap-highlight-color: transparent;
input[type="range"]{
-webkit-tap-highlight-color: transparent;
}
_x000D_
<input type="range" id="volume" name="demo"
min="0" max="11">
<label for="volume">Demo</label>
_x000D_
If you use Alamofire, it is enough to encoding type to "URLEncoding.httpBody"
With that, you can send your data as a string in the httpbody allthough you defined it json in your code.
It worked for me..
UPDATED for
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
You could have the batch file change the current working directory (CD).
Parameter int defStyleAttr
does not specifies the style. From the Android documentation:
defStyleAttr - An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
To setup the style in View constructor we have 2 possible solutions:
With use of ContextThemeWrapper:
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style);
TextView textView = new TextView(wrappedContext, null, 0);
With four-argument constructor (available starting from LOLLIPOP):
TextView textView = new TextView(yourContext, null, 0, R.style.your_style);
Key thing for both solutions - defStyleAttr
parameter should be 0 to apply our style to the view.
JMyron is very simple for use. http://webcamxtra.sourceforge.net/
myron = new JMyron();
myron.start(imgw, imgh);
myron.update();
int[] img = myron.image();
make sure your app is live on developer.facebook.com
This green circle is indicating the app is live
If it is not then follow this two steps for make your app live
Step 1 Go to your application -> setting => and add Contact Email and apply save Changes
Setp 2 Then goto App Review option and make sure this toggle is Yes i added a screen shot
I tried the other solutions here, they work but I'm lazy so this is my solution
by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely
Also you can try zenity !
user=$(zenity --entry --text 'Please enter the username:') || exit 1
from threading import Thread
from time import sleep
def run(name):
for x in range(10):
print("helo "+name)
sleep(1)
def run1():
for x in range(10):
print("hi")
sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")
To insert a single row of data:
INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');
To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');
To insert multiple rows of data in SQL Server 2008 or later:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');
To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'
Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.
Just saying, this is also the value (kind of...) that is returned from php upon:
<?php var_dump(urlencode(PHP_EOL)); ?>
// Prints: string '%0D%0A' (length=6)-- used in 5.4.24 at least
For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}'
was working fine but unable to store output of command into variable.
I had same issue I tried eval
but didn't got output.
Here is answer for my problem:
cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')
echo $cmd
My output is now 20200824
I suggest using:
command $(echo $(tr '\n' ' ' < parameters.cfg))
Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
And what about using Open XML SDK 2.0 for Microsoft Office?
A few benefits:
Links:
$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);
Array ( [0] => apple [1] => cherry )
//...
array_multisort($result, SORT_DESC);
//...
Array ( [0] => cherry [1] => apple )
I know this is a late answer, but I found this question because I had the same problem. I think I found the answer in this post on lexandera.com. The code below is basically a cut-and-paste from the site. It seems to do the trick.
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
@JavascriptInterface
@SuppressWarnings("unused")
public void processHTML(String html)
{
// process the html as needed by the app
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
Here an example:
final AtomicInteger counter = new AtomicInteger();
final int partitionSize=3;
final List<Object> list=new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
final Collection<List<Object>> subLists=list.stream().collect(Collectors.groupingBy
(it->counter.getAndIncrement() / partitionSize))
.values();
System.out.println(subLists);
Input: [A, B, C, D, E]
Output: [[A, B, C], [D, E]]
You can find examples here: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/
How about this:
When the page first loads, do this:
var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;
Then when you want to clear the table:
myTable.innerHTML=myTable.oldHTML;
The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.
The typical way is with scanf
:
int input_value;
scanf("%d", &input_value);
In most cases, however, you want to check whether your attempt at reading input succeeded. scanf
returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
Of course, the same is true of all the scanf
family (sscanf
, fscanf
and so on).
Here's a little cmd script you can copy-n-paste into a file named something like where.cmd
:
@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem The main ideas for this script were taken from Raymond Chen's blog:
rem
rem http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem help diagnose situations with a conflict of some sort.
rem
setlocal
rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%
if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok
rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
Regarding this link you can make the first solution provided by krzyk permanent by executing:
echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile
source ~/.bash_profile
I think the best method :)
int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
angle = angle + 90;
imageView.setRotation(angle);
}
});
For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>
<Directory "C:/wamp/www">
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
</Directory>
You can find the answer in this video https://www.youtube.com/watch?v=SYoN-OvdZ3M&list=PLonJJ3BVjZW6CtAMbJz1XD8ELUs1KXaTD&index=19 and the next 3 videos. All the touch events are explained very well, it's very clear and full of examples.
1.For Chrome & IE
<script language="javascript">
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.getElementById('header').style.display = 'none';
document.getElementById('footer').style.display = 'none';
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<div id="div_print">
<div id="header" style="background-color:White;"></div>
<div id="footer" style="background-color:White;"></div>
</div>
Add moznomarginboxes attribute in Example :
<html moznomarginboxes mozdisallowselectionprint>
Conditional imports could also be achieved with a ternary and require()
s:
const logger = DEBUG ? require('dev-logger') : require('logger');
This example was taken from the ES Lint global-require docs: https://eslint.org/docs/rules/global-require
I suggest
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
Check this demo.
Even to get a sorted unique value, it can be done using formula. This is an option you can use:
=INDEX($A$2:$A$18,MATCH(SUM(COUNTIF($A$2:$A$18,C$1:C1)),COUNTIF($A$2:$A$18,"<" &$A$2:$A$18),0))
range data: A2:A18
formula in cell C2
This is an ARRAY FORMULA
SQL Server functions, like cursors, are meant to be used as your last weapon! They do have performance issues and therefore using a table-valued function should be avoided as much as possible. Talking about performance is talking about a table with more than 1,000,000 records hosted on a server on a middle-class hardware; otherwise you don't need to worry about the performance hit caused by the functions.
for further reference see: http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html
This allows to show time in input field but hides time picker button, which is second li element in accordion
.bootstrap-datetimepicker-widget .list-unstyled li:nth-child(2){
display: none;
}
Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.
In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden')
which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.
If you're here from Google and are experiencing this issue with GFI MailEssentials's config export tool, check to make sure you aren't trying to open WebMon.SettingsImporterTool.exe.xml instead of WebMon.SettingsImporterTool.exe
If you have "hide common file extensions" enabled, you will see the .exe but not the .xml
You can turn an array into a stream by using Arrays.stream()
:
int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);
Once you've got your stream, you can use any of the methods described in the documentation, like sum()
or whatever. You can map
or filter
like in Python by calling the relevant stream methods with a Lambda function:
Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);
Once you're done modifying your stream, you then call toArray()
to convert it back into an array to use elsewhere:
int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();
also, you can fetch all data and count in the blade file. for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on script tags. Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results.
http://en.wikipedia.org/wiki/JSONP
Good answer on stackoverflow: jQuery AJAX cross domain
$.ajax({
type: "GET",
url: 'http://www.oxfordlearnersdictionaries.com/search/english/direct/',
data:{q:idiom},
async:true,
dataType : 'jsonp', //you may use jsonp for cross origin request
crossDomain:true,
success: function(data, status, xhr) {
alert(xhr.getResponseHeader('Location'));
}
});
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
You probably mean Notification.Builder.setLargeIcon(Bitmap)
, right? :)
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);
This is a great method of converting resource images into Android Bitmap
s.
This is also an alternate use of case-when...
UPDATE [dbo].[JobTemplates]
SET [CycleId] =
CASE [Id]
WHEN 1376 THEN 44 --ACE1 FX1
WHEN 1385 THEN 44 --ACE1 FX2
WHEN 1574 THEN 43 --ACE1 ELEM1
WHEN 1576 THEN 43 --ACE1 ELEM2
WHEN 1581 THEN 41 --ACE1 FS1
WHEN 1585 THEN 42 --ACE1 HS1
WHEN 1588 THEN 43 --ACE1 RS1
WHEN 1589 THEN 44 --ACE1 RM1
WHEN 1590 THEN 43 --ACE1 ELEM3
WHEN 1591 THEN 43 --ACE1 ELEM4
WHEN 1595 THEN 44 --ACE1 SSTn
ELSE 0
END
WHERE
[Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)
I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:
SELECT
[Id]
,[QueueId]
,[BaseDimensionId]
,[ElastomerTypeId]
,CASE [CycleId]
WHEN 29 THEN 44
WHEN 30 THEN 43
WHEN 31 THEN 43
WHEN 101 THEN 41
WHEN 102 THEN 43
WHEN 116 THEN 42
WHEN 120 THEN 44
WHEN 127 THEN 44
WHEN 129 THEN 44
ELSE 0
END AS [CycleId]
INTO
##ACE1_PQPANominals_1
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
[QueueId] = 3
ORDER BY
[BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)
UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET
[CycleId] = X.[CycleId]
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
SELECT
MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
FROM
##ACE1_PQPANominals_1
GROUP BY
[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
) AS X
ON
[dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)
The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
decoration: InputDecoration(
border:OutLineInputBorder(
borderSide:BorderSide.none
bordeRadius: BordeRadius.circular(20.0)
)
)
Conditional Forms
Simple
conditional-directive
text-if-true
endif
Moderately Complex
conditional-directive
text-if-true
else
text-if-false
endif
More Complex
conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif
Conditional Directives
If Equal Syntax
ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"
If Not Equal Syntax
ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"
If Defined Syntax
ifdef variable-name
If Not Defined Syntax
ifndef variable-name
foreach Function
foreach Function Syntax
$(foreach var, list, text)
foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.
One way using awk
:
tail -f file.txt | awk '/A1/ { print $NF }'
You should iterate over the keys and get the values using square brackets.
See: How do I enumerate the properties of a javascript object?
EDIT: Obviously, this makes the question a duplicate.
Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system
or exec
for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.
I was looking for slightly different task, but this looks like what you want:
git archive --remote=$REPO_URL HEAD:$DIR_NAME -- $FILE_NAME |
tar xO > /where/you/want/to/have.it
I mean, if you want to fetch path/to/file.xz
, you will set DIR_NAME
to path/to
and FILE_NAME
to file.xz
.
So, you'll end up with something like
git archive --remote=$REPO_URL HEAD:path/to -- file.xz |
tar xO > /where/you/want/to/have.it
And nobody keeps you from any other form of unpacking instead of tar xO
of course (It was me who need a pipe here, yeah).
When converting from signed to unsigned there are two possibilities. Numbers that were originally positive remain (or are interpreted as) the same value. Number that were originally negative will now be interpreted as larger positive numbers.
You can add a style.css
, import this file after the bootstrap.css
to override this code.
For example:
/* bootstrap.css */
* {
font-size: 14px;
line-height: 1.428;
}
/* style.css */
* {
font-size: 16px;
line-height: 2;
}
Don't change bootstrap.css
directly for better maintenance of code.
Now there's the s (single line) modifier, that lets the dot matches new lines as well :) \s will also match new lines :D
Just add the s behind the slash
/<pre.*?<\/pre>/gms
This is more of a mathematical approach but it works 100% of the time:
Let's say you want to use random.random()
function to generate a number between a
and b
. To achieve this, just do the following:
num = (b-a)*random.random() + a;
Of course, you can generate more numbers.
I'm writing an answer to increase visibility to the actual syntax that solves the problem. Unfortunately, what someone might see as trivial can become a very significant headache to someone looking for a simple answer to a reasonable question.
Put the following into the file "Makefile".
MY_VAR := $(shell python -c 'import sys; print int(sys.version_info >= (2,5))')
all:
@echo MY_VAR IS $(MY_VAR)
The behavior you would like to see is the following (assuming you have recent python installed).
make
MY_VAR IS 1
If you copy and paste the above text into the Makefile, will you get this? Probably not. You will probably get an error like what is reported here:
makefile:4: *** missing separator. Stop
Why: Because although I personally used a genuine tab, Stack Overflow (attempting to be helpful) converts my tab into a number of spaces. You, frustrated internet citizen, now copy this, thinking that you now have the same text that I used. The make command, now reads the spaces and finds that the "all" command is incorrectly formatted. So copy the above text, paste it, and then convert the whitespace before "@echo" to a tab, and this example should, at last, hopefully, work for you.
Create Table:
Create Table EmployeeProfile (
EmpId int,
EmpName varchar(50) not null,
EmpPhoto varbinary(max) not null )
Go
Insert statement:
Insert EmployeeProfile
(EmpId, EmpName, EmpPhoto)
Select 1001, 'Vadivel', BulkColumn
from Openrowset( Bulk 'C:\Image1.jpg', Single_Blob) as EmployeePicture
This Sql Query Working Fine.
Taking into account that you want to resize to exact size and want to keep as much quality as needed I think you should try this.
Motivation: multiple-steps scaling could give you higher quality picture, however there is no guarantee that it will work better than using high inSampleSize. Actually, I think that you also can use inSampleSize like 5 (not pow of 2) to have direct scaling in one operation. Or just use 4 and then you can just use that image in UI. if you send it to server - than you can do scaling to exact size on server side which allow you to use advanced scaling techniques.
Notes: if the Bitmap loaded in step-3 is at least 4 times larger (so the 4*targetWidth < width) you probably can use several resizing to achieve better quality. at least that works in generic java, in android you don't have the option to specify the interpolation used for scaling http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
Besides, multiline comments are a bitch. Sorry to say, but regardless of the language, I don't use them for anything else than debugging purposes. Say you have code like this:
void someFunction()
{
Something
/*Some comments*/
Something else
}
Then you find out that there is something in your code you can't fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:
void someFunction()
{ /*
Something
/* Comments */
Something more*/
}
This is really irritating.
For Passing a single variable to view.
Inside Your controller create a method like:
function sleep()
{
return view('welcome')->with('title','My App');
}
In Your route
Route::get('/sleep', 'TestController@sleep');
In Your View Welcome.blade.php
. You can echo your variable like {{ $title }}
For An Array(multiple values) change,sleep method to :
function sleep()
{
$data = array(
'title'=>'My App',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('welcome')->with($data);
}
You can access you variable like {{ $author }}
.
Look in the SDK Manager what is your highest Android SDK Build-tools
version, and copy this version number in your project build.gradle
file, in the android/buildToolsVersion
property (for me, version was "18.1.1").
Hope it help!
try this one
npm cache clean --force
after that run
npm cache verify
as @Jörg W Mittag pointed out: in jruby, fix num size is always 8 bytes long. This code snippet shows the truth:
fmax = ->{
if RUBY_PLATFORM == 'java'
2**63 - 1
else
2**(0.size * 8 - 2) - 1
end
}.call
p fmax.class # Fixnum
fmax = fmax + 1
p fmax.class #Bignum
You need to use the property /a
on the set command.
For example,
set /a "c=%a%+%b%"
This allows you to use arithmetic expressions in the set command, rather than simple concatenation.
Your code would then be:
@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%
and would output:
7
8
to upgrade php7 to latest stable version brew upgrade php7
or for php5.X to latest stable version
brew upgrade php56
use brew list
to check installed version
You could be lazy, and wrap it in a lambda
:
my_hash = YAML.load_file('yml')
my_lamb = lambda { |key| my_hash[key.to_s] }
my_lamb[:a] == my_hash['a'] #=> true
But this would only work for reading from the hash - not writing.
To do that, you could use Hash#merge
my_hash = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(YAML.load_file('yml'))
The init block will convert the keys one time on demand, though if you update the value for the string version of the key after accessing the symbol version, the symbol version won't be updated.
irb> x = { 'a' => 1, 'b' => 2 }
#=> {"a"=>1, "b"=>2}
irb> y = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(x)
#=> {"a"=>1, "b"=>2}
irb> y[:a] # the key :a doesn't exist for y, so the init block is called
#=> 1
irb> y
#=> {"a"=>1, :a=>1, "b"=>2}
irb> y[:a] # the key :a now exists for y, so the init block is isn't called
#=> 1
irb> y['a'] = 3
#=> 3
irb> y
#=> {"a"=>3, :a=>1, "b"=>2}
You could also have the init block not update the hash, which would protect you from that kind of error, but you'd still be vulnerable to the opposite - updating the symbol version wouldn't update the string version:
irb> q = { 'c' => 4, 'd' => 5 }
#=> {"c"=>4, "d"=>5}
irb> r = Hash.new { |h,k| h[k.to_s] }.merge(q)
#=> {"c"=>4, "d"=>5}
irb> r[:c] # init block is called
#=> 4
irb> r
#=> {"c"=>4, "d"=>5}
irb> r[:c] # init block is called again, since this key still isn't in r
#=> 4
irb> r[:c] = 7
#=> 7
irb> r
#=> {:c=>7, "c"=>4, "d"=>5}
So the thing to be careful of with these is switching between the two key forms. Stick with one.
Here is my observation. I created a login (readonly) for a group windows(AD) user account but, its acting defiantly in different SQL servers. In the SQl servers that users can not see the databases I added view definition checked and also gave database execute permeation to the master database for avoiding error 229. I do not have this issue if I create a login for a user.
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
Simple Soltion
UPDATE `table_name`
SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')
Above many of the answers are good but none of the worked for me fully. So i combined the answer from @nmr and got this one.
final Dialog d = new Dialog(getActivity());
// d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.dialog_box_shipment_detail);
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
Display display = wm.getDefaultDisplay(); // getting the screen size of device
Point size = new Point();
display.getSize(size);
int width = size.x - 20; // Set your heights
int height = size.y - 80; // set your widths
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = width;
lp.height = height;
d.getWindow().setAttributes(lp);
d.show();
Here is my version of animated image control. You can use standard property Source for specifying image source. I further improved it. I am a russian, project is russian so comments are also in Russian. But anyway you should be able understand everything without comments. :)
/// <summary>
/// Control the "Images", which supports animated GIF.
/// </summary>
public class AnimatedImage : Image
{
#region Public properties
/// <summary>
/// Gets / sets the number of the current frame.
/// </summary>
public int FrameIndex
{
get { return (int) GetValue(FrameIndexProperty); }
set { SetValue(FrameIndexProperty, value); }
}
/// <summary>
/// Gets / sets the image that will be drawn.
/// </summary>
public new ImageSource Source
{
get { return (ImageSource) GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
#endregion
#region Protected interface
/// <summary>
/// Provides derived classes an opportunity to handle changes to the Source property.
/// </summary>
protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs aEventArgs)
{
ClearAnimation();
BitmapImage lBitmapImage = aEventArgs.NewValue as BitmapImage;
if (lBitmapImage == null)
{
ImageSource lImageSource = aEventArgs.NewValue as ImageSource;
base.Source = lImageSource;
return;
}
if (!IsAnimatedGifImage(lBitmapImage))
{
base.Source = lBitmapImage;
return;
}
PrepareAnimation(lBitmapImage);
}
#endregion
#region Private properties
private Int32Animation Animation { get; set; }
private GifBitmapDecoder Decoder { get; set; }
private bool IsAnimationWorking { get; set; }
#endregion
#region Private methods
private void ClearAnimation()
{
if (Animation != null)
{
BeginAnimation(FrameIndexProperty, null);
}
IsAnimationWorking = false;
Animation = null;
Decoder = null;
}
private void PrepareAnimation(BitmapImage aBitmapImage)
{
Debug.Assert(aBitmapImage != null);
if (aBitmapImage.UriSource != null)
{
Decoder = new GifBitmapDecoder(
aBitmapImage.UriSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
}
else
{
aBitmapImage.StreamSource.Position = 0;
Decoder = new GifBitmapDecoder(
aBitmapImage.StreamSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
}
Animation =
new Int32Animation(
0,
Decoder.Frames.Count - 1,
new Duration(
new TimeSpan(
0,
0,
0,
Decoder.Frames.Count / 10,
(int) ((Decoder.Frames.Count / 10.0 - Decoder.Frames.Count / 10) * 1000))))
{
RepeatBehavior = RepeatBehavior.Forever
};
base.Source = Decoder.Frames[0];
BeginAnimation(FrameIndexProperty, Animation);
IsAnimationWorking = true;
}
private bool IsAnimatedGifImage(BitmapImage aBitmapImage)
{
Debug.Assert(aBitmapImage != null);
bool lResult = false;
if (aBitmapImage.UriSource != null)
{
BitmapDecoder lBitmapDecoder = BitmapDecoder.Create(
aBitmapImage.UriSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
lResult = lBitmapDecoder is GifBitmapDecoder;
}
else if (aBitmapImage.StreamSource != null)
{
try
{
long lStreamPosition = aBitmapImage.StreamSource.Position;
aBitmapImage.StreamSource.Position = 0;
GifBitmapDecoder lBitmapDecoder =
new GifBitmapDecoder(
aBitmapImage.StreamSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
lResult = lBitmapDecoder.Frames.Count > 1;
aBitmapImage.StreamSource.Position = lStreamPosition;
}
catch
{
lResult = false;
}
}
return lResult;
}
private static void ChangingFrameIndex
(DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)
{
AnimatedImage lAnimatedImage = aObject as AnimatedImage;
if (lAnimatedImage == null || !lAnimatedImage.IsAnimationWorking)
{
return;
}
int lFrameIndex = (int) aEventArgs.NewValue;
((Image) lAnimatedImage).Source = lAnimatedImage.Decoder.Frames[lFrameIndex];
lAnimatedImage.InvalidateVisual();
}
/// <summary>
/// Handles changes to the Source property.
/// </summary>
private static void OnSourceChanged
(DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)
{
((AnimatedImage) aObject).OnSourceChanged(aEventArgs);
}
#endregion
#region Dependency Properties
/// <summary>
/// FrameIndex Dependency Property
/// </summary>
public static readonly DependencyProperty FrameIndexProperty =
DependencyProperty.Register(
"FrameIndex",
typeof (int),
typeof (AnimatedImage),
new UIPropertyMetadata(0, ChangingFrameIndex));
/// <summary>
/// Source Dependency Property
/// </summary>
public new static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
"Source",
typeof (ImageSource),
typeof (AnimatedImage),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure,
OnSourceChanged));
#endregion
}
The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse
with Java libraries.
Here is the more complete code :
/*
* Create the POST request
*/
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
Consider:
^\+?[0-9]{3}-?[0-9]{6,12}$
This only allows +
at the beginning; it requires 3 digits, followed by an optional dash, followed by 6-12 more digits.
Note that the original regex allows 'phone numbers' such as 70+12---12+92
, which is a bit more liberal than you probably had in mind.
The question was amended to add:
+077-1-23-45-67 and +077-123-45-6-7
You now probably need to be using a regex system that supports alternatives:
^\+?[0-9]{3}-?([0-9]{7}|[0-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}|[0-9]{3}-[0-9]{2}-[0-9]-[0-9])$
The first alternative is seven digits; the second is 1-23-45-67; the third is 123-45-6-7. These all share the optional plus +
followed by 3 digits and an optional dash -
prefix.
The comment below mentions another pattern:
+077-12-34-567
It is not at all clear what the general pattern should be - maybe one or more digits separated by dashes; digits at front and back?
^\+?[0-9]{3}-?[0-9](-[0-9]+)+$
This will allow the '+077-' prefix, followed by any sequence of digits alternating with dashes, with at least one digit between each dash and no dash at the end.
cat * | grep -c string
One of the rare useful applications of cat
.
Yes, we can zip and unzip the file/folder using cmd. See the below command and simply you can copy past in cmd and change the directory and file name
To Zip/Compress File
powershell Compress-Archive D:\Build\FolderName D:\Build\FolderName.zip
To Unzip/Expand File
powershell expand-archive D:\Build\FileName.zip D:\deployments\FileName
Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?
As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
insert='insert into Songs ({0}) values ({1})'.
.format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) ))
args = [ meta[i] for i in meta_cols ]
cursor=db.cursor()
cursor.execute(insert,args)
db.commit()
Where meta is the dictionary holding the values to insert. Update can be done in the same way:
meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
update='update Songs set {0} where id=%s'.
.format(','.join([ '{0}=%s'.format(c) for c in meta_cols ]))
args = [ meta[i] for i in meta_cols ]
args.append( songid )
cursor=db.cursor()
cursor.execute(update,args)
db.commit()
Visual Basic Version:
Private Sub setRegisterForWebBrowser()
Dim appName = Process.GetCurrentProcess().ProcessName + ".exe"
SetIE8KeyforWebBrowserControl(appName)
End Sub
Private Sub SetIE8KeyforWebBrowserControl(appName As String)
'ref: http://stackoverflow.com/questions/17922308/use-latest-version-of-ie-in-webbrowser-control
Dim Regkey As RegistryKey = Nothing
Dim lgValue As Long = 8000
Dim strValue As Long = lgValue.ToString()
Try
'For 64 bit Machine
If (Environment.Is64BitOperatingSystem) Then
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", True)
Else 'For 32 bit Machine
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", True)
End If
'If the path Is Not correct Or
'If user't have priviledges to access registry
If (Regkey Is Nothing) Then
MessageBox.Show("Application Settings Failed - Address Not found")
Return
End If
Dim FindAppkey As String = Convert.ToString(Regkey.GetValue(appName))
'Check if key Is already present
If (FindAppkey = strValue) Then
MessageBox.Show("Required Application Settings Present")
Regkey.Close()
Return
End If
'If key Is Not present add the key , Kev value 8000-Decimal
If (String.IsNullOrEmpty(FindAppkey)) Then
' Regkey.SetValue(appName, BitConverter.GetBytes(&H1F40), RegistryValueKind.DWord)
Regkey.SetValue(appName, lgValue, RegistryValueKind.DWord)
'check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName))
End If
If (FindAppkey = strValue) Then
MessageBox.Show("Registre de l'application appliquée avec succès")
Else
MessageBox.Show("Échec du paramètrage du registre, Ref: " + FindAppkey)
End If
Catch ex As Exception
MessageBox.Show("Application Settings Failed")
MessageBox.Show(ex.Message)
Finally
'Close the Registry
If (Not Regkey Is Nothing) Then
Regkey.Close()
End If
End Try
End Sub
Specifying a non-static position, e.g., position: absolute/relative
on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/
See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts
We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.
#outer {_x000D_
min-width: 2000px; _x000D_
min-height: 1000px; _x000D_
background: #3e3e3e; _x000D_
position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
left: 1%; _x000D_
top: 45px; _x000D_
width: 50%; _x000D_
height: auto; _x000D_
position: absolute; _x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
background: #efffef;_x000D_
position: absolute; _x000D_
height: 400px; _x000D_
right: 0px; _x000D_
left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">_x000D_
<div id="inner-inner"></div>_x000D_
</div>_x000D_
</div>
_x000D_
new Function('alert("Hello")')();
I think this is the best way.
In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:
conda install openpyxl
Easy and simple:
public static bool DirIsEmpty(string path) {
int num = Directory.GetFiles(path).Length + Directory.GetDirectories(path).Length;
return num == 0;
}
Alex, Gary:
As requested, here is my comment posted as an answer:
var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));
Thanks for letting me know.
In pseudo code that can be expressed as:
The right offset is:
The window's width MINUS
( The element's left offset PLUS the element's outer width )
Intro: I assume that you have a matrix X
where each row/line is a sample/observation and each column is a variable/feature (this is the expected input for any sklearn
ML function by the way -- X.shape
should be [number_of_samples, number_of_features]
).
Core of method: The main idea is to normalize/standardize i.e. µ = 0
and s = 1
your features/variables/columns of X
, individually, before applying any machine learning model.
StandardScaler()
will normalize the features i.e. each column of X, INDIVIDUALLY, so that each column/feature/variable will have µ = 0
and s = 1
.
P.S: I find the most upvoted answer on this page, wrong. I am quoting "each value in the dataset will have the sample mean value subtracted" -- This is neither true nor correct.
See also: How and why to Standardize your data: A python tutorial
Example:
from sklearn.preprocessing import StandardScaler
import numpy as np
# 4 samples/observations and 2 variables/features
data = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
scaler = StandardScaler()
scaled_data = scaler.fit_transform(data)
print(data)
[[0, 0],
[1, 0],
[0, 1],
[1, 1]])
print(scaled_data)
[[-1. -1.]
[ 1. -1.]
[-1. 1.]
[ 1. 1.]]
Verify that the mean of each feature (column) is 0:
scaled_data.mean(axis = 0)
array([0., 0.])
Verify that the std of each feature (column) is 1:
scaled_data.std(axis = 0)
array([1., 1.])
The maths:
UPDATE 08/2020: Concerning the input parameters with_mean
and with_std
to False
/True
, I have provided an answer here: StandardScaler difference between “with_std=False or True” and “with_mean=False or True”
With Lodash:
_.omitBy({a: 1, b: null}, (v) => !v)
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
Check out the help command:
svn help copy
-r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)
A revision argument can be one of:
NUMBER revision number
'{' DATE '}' revision at start of the date
'HEAD' latest in repository
'BASE' base rev of item's working copy
'COMMITTED' last commit at or before BASE
'PREV' revision just before COMMITTED
To actually specify this on the command line using your example:
svn copy -r123 http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
Where 123
would be the revision number in trunk you want to copy. As others have noted, you can also use the @ syntax. I prefer the clearer separation of the revision # from the URL, personally.
As noted in the help, you can replace a revision # with certain words as well:
svn copy -rPREV http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
Would copy the "revision just before COMMITTED".
Use String.PadLeft, if your desired string contains only a single char.
public static string Indent(int count, char pad)
{
return String.Empty.PadLeft(count, pad);
}
Credit due here
arange
generates lists (well, numpy arrays); type help(np.arange)
for the details. You don't need to call it on existing lists.
>>> x = [1,2,3,4]
>>> y = [3,5,7,9]
>>>
>>> m,b = np.polyfit(x, y, 1)
>>> m
2.0000000000000009
>>> b
0.99999999999999833
I should add that I tend to use poly1d
here rather than write out "m*x+b" and the higher-order equivalents, so my version of your code would look something like this:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [3,5,7,10] # 10, not 9, so the fit isn't perfect
coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef)
# poly1d_fn is now a function which takes in x and returns an estimate for y
plt.plot(x,y, 'yo', x, poly1d_fn(x), '--k')
plt.xlim(0, 5)
plt.ylim(0, 12)
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss
).
Also, you need to specify H
instead of h
if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
for china GFW:
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
#This valid till 4 digit number
numbers={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen',
17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty',
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand'}
def my_fun(num):
list = []
num_len = len(str(num)) - 1
while num_len > 0 and num > 0:
while num_len > 0 and num > 0:
if num in numbers and num < 1000:
list.append(numbers[num])
num_len = 0
elif num < 100:
list.extend([numbers[num - num%10], numbers[num%10]])
num_len = 0
else:
quotent = num//10**num_len # 4567//1000= 4
num = num % 10**num_len #4567%1000 =567
if quotent != 0 :
list.append(numbers[quotent])
list.append(numbers[10**num_len])
else:
list.append(numbers[num])
num_len -= 1
return ' '.join(list)
Here is a defaultdict
solution that will work with Python versions 2.5 and above:
from collections import defaultdict
L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times
Note if L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67]
then there are six 4s and six 7s. However, the result will be (4, 6)
i.e. six 4s.
#change-avatar-file
is a file input
#change-avatar-file
is a img tag (the target of jcrop)
The "key" is FR.onloadend Event
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
$('#change-avatar-file').change(function(){
var currentImg;
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
$('#avatar-change-img').attr( "src", e.target.result );
currentImg = e.target.result;
};
FR.readAsDataURL( this.files[0] );
FR.onloadend = function(e){
//console.log( $('#avatar-change-img').attr( "src"));
var jcrop_api;
$('#avatar-change-img').Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [ 60, 70, 540, 330 ]
},function(){
jcrop_api = this;
});
}
}
});
success
has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds
and more sophisticated callbacks, done
is the preferred way to implement success callbacks, as it can be called on any deferred
.
For example, success:
$.ajax({
url: '/',
success: function(data) {}
});
For example, done:
$.ajax({url: '/'}).done(function(data) {});
The nice thing about done
is that the return value of $.ajax
is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax
itself and bind your callbacks with done
, fail
, then
, or whatever. Note that always
is a callback that will run whether the request succeeds or fails. done
will only be triggered on success.
For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax
call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get
definition (being sure to return a promise or at least a done
method, in the case of the example above). All the other references throughout the app can remain the same.
There are many more (much cooler) things you can do with $.Deferred
, one of which is to use pipe
to trigger a failure on an error reported by the server, even when the $.ajax
request itself succeeds. For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json'
})
.pipe(function(data) {
return data.responseCode != 200 ?
$.Deferred().reject( data ) :
data;
})
.fail(function(data) {
if ( data.responseCode )
console.log( data.responseCode );
});
}
xhr_get('/index').done(function(data) {
// will not run if json returned from ajax has responseCode other than 200
});
Read more about $.Deferred
here: http://api.jquery.com/category/deferred-object/
NOTE: As of jQuery 1.8, pipe
has been deprecated in favor of using then
in exactly the same way.
I'm writing slider ui control to provide drag feature, this is my way to prevent content from selecting when user is dragging:
function disableSelect(event) {
event.preventDefault();
}
function startDrag(event) {
window.addEventListener('mouseup', onDragEnd);
window.addEventListener('selectstart', disableSelect);
// ... my other code
}
function onDragEnd() {
window.removeEventListener('mouseup', onDragEnd);
window.removeEventListener('selectstart', disableSelect);
// ... my other code
}
bind startDrag
on your dom:
<button onmousedown="startDrag">...</button>
If you want to statically disable text select on all element, execute the code when elements are loaded:
window.addEventListener('selectstart', function(e){ e.preventDefault(); });
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
Yeah.ios supports RGB valur to range between 0 and 1 only..its close Range [0,1]
You can use strcpy to populate it. You can also initialize it from another struct.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct name {
char first[20];
char last[20];
};
int main() {
struct name sara;
struct name other;
strcpy(sara.first,"Sara");
strcpy(sara.last, "Black");
other = sara;
printf("struct: %s\t%s\n", sara.first, sara.last);
printf("other struct: %s\t%s\n", other.first, other.last);
}
I don't like my switch
statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case
statements all do exactly the same thing.
If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.
In simple words
v-model
is for two way bindings means: if you change input value, the bound data will be changed and vice versa.
but v-bind:value
is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.
check out this simple example: https://jsfiddle.net/gs0kphvc/
I had to clear
C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files
Only then did the issue get resolved.
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
This worked fine for me
int max = Convert.ToInt32(datatable_name.AsEnumerable()
.Max(row => row["column_Name"]));
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
This might help
import binascii
x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')
print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374
x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'
x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test
This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii')
.
Using generics (as in the above answers) is your best bet here. I've just double checked and:
test.put("test", arraylistone);
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");
will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.
Hope this code helps you out :)
public class MainActivity extends Activity {
private int mMessageSentParts;
private int mMessageSentTotalParts;
private int mMessageSentCount;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String phoneNumber = "0000000000";
String message = "Hello World!";
sendSMS(phoneNumber,message);
}
});
}
public void sendSMS(String phoneNumber,String message) {
SmsManager smsManager = SmsManager.getDefault();
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
int messageCount = parts.size();
Log.i("Message Count", "Message Count: " + messageCount);
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
for (int j = 0; j < messageCount; j++) {
sentIntents.add(sentPI);
deliveryIntents.add(deliveredPI);
}
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
// ---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
smsManager.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
/* sms.sendMultipartTextMessage(phoneNumber, null, parts, sentIntents, deliveryIntents); */
}
}
This line looks suspicious:
invaders[i] = inv;
You're never incrementing i
, so you keep assigning to invaders[0]
. If this is just an error you made when reducing your code to the example, check how you calculate i
in the real code; you could be exceeding the size of invaders
.
If as your comment suggests, you're creating 55 invaders
, then check that invaders
has been initialised correctly to handle this number.
Here is my backup script that will give you the idea and the automation:
Server: Ubuntu 16.04 PHP: 7.0 Apache2, Mysql etc...
# Make Shell Backup Script - Bash Backup Script
nano /home/user/bash/backupscript.sh
#!/bin/bash
# Backup All Start
mkdir /home/user/backup/$(date +"%Y-%m-%d")
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
# Backup All End
echo "Backup Completed Successfully!"
echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"
chmod +x /home/user/bash/backupscript.sh
sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript
change /home/user to your user directory and type: backupscript anywhere on terminal to run the script! (assuming that /usr/bin is in your path)
There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.
$ sbt sbtVersion
This prints the sbt version used in your current project, or if it is a multi-module project for each module.
$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info] Provides the version of sbt. This setting should be not be modified.
[info] Provided by:
[info] */*:sbtVersion
[info] Defined at:
[info] (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info] *:sbtVersion
[info] {.}/*:sbtVersion
[info] */*:sbtVersion
[info] Related:
[info] */*:sbtVersion
You may also want to use sbt about
that (copying Mark Harrah's comment):
The about command was added recently to try to succinctly print the most relevant information, including the sbt version.
import random
result=[]
for i in range(1,50):
rng=random.randint(1,20)
result.append(rng)
It does not work because your foobar.go
source file is not in a directory called foobar
. go build
and go install
try to match directories, not source files.
$GOPATH
to a valid directory, e.g. export GOPATH="$HOME/go"
foobar.go
to $GOPATH/src/foobar/foobar.go
and building should work just fine.Additional recommended steps:
$GOPATH/bin
to your $PATH
by: PATH="$GOPATH/bin:$PATH"
main.go
to a subfolder of $GOPATH/src
, e.g. $GOPATH/src/test
go install test
should now create an executable in $GOPATH/bin
that can be called by typing test
into your terminal.Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url
to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
Others have already explained this well. Let me give you an animation which will explain this quickly: http://codepen.io/chriscoyier/pen/lotjh
Here is some code for you to play with and learn the concepts.
HTML:
<html>
<body>
<div id="border-demo">
</div>
</body>
</html>
CSS:
/*border-width is border thickness*/
#border-demo {
background: gray;
border-color: yellow blue red green;/*top right bottom left*/
border-style: solid;
border-width: 25px 25px 25px 25px;/*top right bottom left*/
height: 50px;
width: 50px;
}
Play with this and see what happens. Set height and width to zero. Then remove top border and make left and right transparent, or just look at the code below to make a css triangle:
#border-demo {
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid blue;
}
Steps to remove directory
git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master
Steps to ignore that folder in next commits
To ignore that folder from next commits make one file in root folder (main project directory where the git is initialized) named .gitignore and put that folder name into it. You can ignore as many files/folders as you want
.gitignore file will look like this
/FolderName
None of the listed solutions in this thread worked for me. I started getting this error after I made some changes to the connection strings section of the web.config file. (My app connects to multiple databases.) I carefully examined what changes I had made are realized I had removed the tag at the top of my list. I restored the tag at the top of my list of connection strings and the problem went away immediately. This site that was getting the error is a application that resides below the main site (https://www.domain.org/MySite). This might not fix the problem for everyone, but it did resolve the problem for me.
I'm not sure if this was your problem but for anyone that's trying to access his web application from his machine and having this problem:
Make sure you're connecting to 127.0.0.1
(a.k.a localhost
) and not to your external IP address.
Your URL should be something like http://localhost:8181/
or http://127.0.0.1:8181
and not http://YourExternalIPaddress:8181/
.
When you connect to your external IP address, you connect to you from the internet, as if you were a stranger (or a hacker).
However when you connect to your localhost, you connect locally as yourself and the block is obviously not needed (& avoided altogether).
This solution worked for me:
var rawBodySaver = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
}
app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));
When I use solution with req.on('data', function(chunk) { });
it not working on chunked request body.
Draggable div not possible only with CSS
, if you want draggable div you must need to use javascript.
Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:
echo CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT
I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.
It looks that in awk, string can be concatenated by printing variable next to each other:
echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal
Guys Please don't make it so complex The simple answer bellow
$date1=date('d_m_y');
$date2='31_12_11';
$date1=str_replace('_', '-', $date1);
$date2=str_replace('_', '-', $date2)
if(strtotime($date1) < strtotime($date2))
echo '1 is small ='.strtotime($date1).','.$date1;
else
echo '2 is small ='.strtotime($date2).','.$date2;
I just have added two more lines with your code
A linked list is a node-based data structure. Each node designed with two portions (Data & Node Reference).Actually, data is always stored in Data portion (Maybe primitive data types eg Int, Float .etc or we can store user-defined data type also eg. Object reference) and similarly Node Reference should also contain the reference to next node, if there is no next node then the chain will end.
This chain will continue up to any node doesn't have a reference point to the next node.
Please find the source code from my tech blog - http://www.algonuts.info/linked-list-program-in-java.html
package info.algonuts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
class LLNode {
int nodeValue;
LLNode childNode;
public LLNode(int nodeValue) {
this.nodeValue = nodeValue;
this.childNode = null;
}
}
class LLCompute {
private static LLNode temp;
private static LLNode previousNode;
private static LLNode newNode;
private static LLNode headNode;
public static void add(int nodeValue) {
newNode = new LLNode(nodeValue);
temp = headNode;
previousNode = temp;
if(temp != null)
{ compute(); }
else
{ headNode = newNode; } //Set headNode
}
private static void compute() {
if(newNode.nodeValue < temp.nodeValue) { //Sorting - Ascending Order
newNode.childNode = temp;
if(temp == headNode)
{ headNode = newNode; }
else if(previousNode != null)
{ previousNode.childNode = newNode; }
}
else
{
if(temp.childNode == null)
{ temp.childNode = newNode; }
else
{
previousNode = temp;
temp = temp.childNode;
compute();
}
}
}
public static void display() {
temp = headNode;
while(temp != null) {
System.out.print(temp.nodeValue+" ");
temp = temp.childNode;
}
}
}
public class LinkedList {
//Entry Point
public static void main(String[] args) {
//First Set Input Values
List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));
Iterator<Integer> ptr = firstIntList.iterator();
while(ptr.hasNext())
{ LLCompute.add(ptr.next()); }
System.out.println("Sort with first Set Values");
LLCompute.display();
System.out.println("\n");
//Second Set Input Values
List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));
ptr = secondIntList.iterator();
while(ptr.hasNext())
{ LLCompute.add(ptr.next()); }
System.out.println("Sort with first & Second Set Values");
LLCompute.display();
System.out.println();
}
}
making a dynamycal width with mobile devices support
http://www.codeography.com/2011/06/14/dynamic-fixed-width-layout-with-css.html
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.
This is a great place to use regular expressions.
By using a regular expression, you can replace all that code with just one line.
You can use the following regex to validate your requirements:
[0-9]*\.?[0-9]*
In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.
You can replace your code with this:
function validate(s) {
var rgx = /^[0-9]*\.?[0-9]*$/;
return s.match(rgx);
}
That code can replace your entire function!
Note that you have to escape the period with a backslash (otherwise it stands for 'any character').
For more reading on using regular expressions with javascript, check this out:
You can also test the above regex here:
Explanation of the regex used above:
The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.
The *
means "zero or more of the previous expression."
[0-9]*
means "zero or more numbers"
The backslash is used as an escape character for the period, because period usually stands for "any character."
The ?
means "zero or one of the previous character."
The ^
represents the beginning of a string.
The $
represents the end of a string.
Starting the regex with ^
and ending it with $
ensures that the entire string adheres to the regex pattern.
Hope this helps!
It does not cause problems but it's a trick to do the same as PreventDefault
when you're way down in the page and an anchor as:
<a href="#" onclick="fn()">click here</a>
you will jump to the top and the URL will have the anchor #
as well, to avoid this we simply return false;
or use javascript:void(0);
regarding your examples
<a onclick="fn()">Does not appear as a link, because there's no href</a>
just do a {text-decoration:underline;}
and you will have "link a-like"
<a href="javascript:void(0)" onclick="fn()">fn is called</a>
<a href="javascript:" onclick="fn()">fn is called too!</a>
it's ok, but in your function
at the end, just return false;
to prevent the default behavior, you don't need to do anything more.
Whilst Elad's solution will work, you can also do it inline:
-moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
-o-animation: fadeinphoto 7s 20s infinite;
animation: fadeinphoto 7s 20s infinite;
The Git GUI for Windows has a window-based application that allows you to paste in locations for ssh keys and repo url etc:
There are at least these two issues I have observed for this problem: 1) It could be either because your sender username or password might not be correct 2) Or it could be as answered by Avinash above, the security condition on the account. Once you try SendMail using SMTP, you normally get a notification in to your account that it may be an unauthorized attempt to access your account, if not user can follow the link to turn the settings to lessSecureApp. Once this is done and smtp SendMail is tried again, it works.
myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Just one sentence to say Instruct Internet Explorer to use its latest rendering engine
<meta http-equiv="x-ua-compatible" content="ie=edge">
The MSDN article lists MVC routing (the example that really clicked the concept for me) among several others. The (formatted) description paragraph reads:
- When reporting errors in code,
- hooking up model-view-controller (MVC) links,
- firing property changed events, etc.,
you often want to capture the string name of a method. Using nameof helps keep your code valid when renaming definitions.
Before you had to use string literals to refer to definitions, which is brittle when renaming code elements because tools do not know to check these string literals.
The accepted / top rated answers already give several excellent concrete examples.
If your textbox is a Required field and have some regex pattern to match and has minlength and maxlength
TestBox code
<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">
Ng-Class to Add
ng-class="{ 'err' : myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"
Here is a one-liner that doesn't need to know the length of the string beforehand:
from functools import partial
from StringIO import StringIO
[l for l in iter(partial(StringIO(data).read, 4), '')]
If you have a file or socket, then you don't need the StringIO wrapper:
[l for l in iter(partial(file_like_object.read, 4), '')]
If you don't want to, can't easily, or can't quickly patch your code, instead, you can force TLS 1.2 usage by your .NET code in the framework.
This isn't my app, but it helped hotfix our older .NET 4.5 app (running on Server 2008r2) to work again with Paypal Payflow Gateway. They must have started forcing connections over to TLS 1.2 on the payflow gateway callbacks between 6/25/18 and 7/8/18.
Details: https://github.com/TheLevelUp/pos-tls-patcher Download: https://github.com/TheLevelUp/pos-tls-patcher/releases
I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.
A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:
Representation of the central controller (assuming there is one).
Representations of elevators
Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.
Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).
Representation of a human and cargo (may be important for factoring in maximal loads)
Representation of the building (in some cases, as certain floors may be blocked at times, etc.)
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
REACT_APP_NOT_SECRET_CODE=abcdef
Note that the variable name must start with REACT_APP_
You can access it from your component with
process.env.REACT_APP_NOT_SECRET_CODE
Sometimes you can reference a Windows "shortcut" file to launch an application instead of using a ".bat" file, and it won't have the residual prompt problem. But it's not as flexible as bat files.
If you have constant URL
I recommend use simplified http-request built on apache http.
You can build your client as following:
private filan static HttpRequest<YourResponseType> httpRequest =
HttpRequestBuilder.createGet(yourUri,YourResponseType)
.build();
public void send(){
ResponseHendler<YourResponseType> rh =
httpRequest.execute(param1, value1, param2, value2);
handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess);
}
public void whenSuccess(ResponseHendler<YourResponseType> rh){
rh.ifHasContent(content -> // your code);
}
public void whenSuccess(ResponseHendler<YourResponseType> rh){
LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText());
}
Note: There are many useful methods to manipulate your response.
NUMERIC(3,2)
means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.
Try NUMERIC(5,2)
- three before, two after the decimal point.
In my environment, I just added the two files to class path. And is work fine.
slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar
A simple use:
Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");
Sample:
Type dogClass = Type.GetType("Animals.Dog, Animals");
The collection used in foreach is immutable. This is very much by design.
As it says on MSDN:
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.
You could wrap the hidden div in another div that will toggle the visibility with onMouseOver and onMouseOut event handlers in JavaScript:
<style type="text/css">
#div1, #div2, #div3 {
visibility: hidden;
}
</style>
<script>
function show(id) {
document.getElementById(id).style.visibility = "visible";
}
function hide(id) {
document.getElementById(id).style.visibility = "hidden";
}
</script>
<div onMouseOver="show('div1')" onMouseOut="hide('div1')">
<div id="div1">Div 1 Content</div>
</div>
<div onMouseOver="show('div2')" onMouseOut="hide('div2')">
<div id="div2">Div 2 Content</div>
</div>
<div onMouseOver="show('div3')" onMouseOut="hide('div3')">
<div id="div3">Div 3 Content</div>
</div>
This doesn't work because NaN
isn't equal to anything, including NaN
. Use pd.isnull(df.var2)
instead.
You should be able to do that with the Batch Task plugin.
An alternative can also be Post build task plugin.
in windows, simply adding shell: true
option solved my problem:
incorrect:
const { spawn } = require('child_process');
const child = spawn('dir');
correct:
const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
This should do the trick:
public int getNumberOfPdfPages(string fileName)
{
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
Regex regex = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
From Rachael's answer and this one too.
In my context, just developed a class abstraction. When my application is launched, i check if localStorage is working by calling getStorage(). This function also return :
In my code i never call localStorage directly. I call cusStoglobal var, i had initialised by calling getStorage().
This way, it works with private browsing or specific Safari versions
function getStorage() {
var storageImpl;
try {
localStorage.setItem("storage", "");
localStorage.removeItem("storage");
storageImpl = localStorage;
}
catch (err) {
storageImpl = new LocalStorageAlternative();
}
return storageImpl;
}
function LocalStorageAlternative() {
var structureLocalStorage = {};
this.setItem = function (key, value) {
structureLocalStorage[key] = value;
}
this.getItem = function (key) {
if(typeof structureLocalStorage[key] != 'undefined' ) {
return structureLocalStorage[key];
}
else {
return null;
}
}
this.removeItem = function (key) {
structureLocalStorage[key] = undefined;
}
}
cusSto = getStorage();
To fully script-automate:
Create:
7z -mhc=on -mhe=on -pPasswordHere a %ZipDest% %WhatYouWantToZip%
Unzip:
7z x %ZipFile% -pPasswordHere
(Depending, you might need to: Set Path=C:\Program Files\7-Zip;%Path% )
For oracle you can
group by trunc(created);
as this truncates the created datetime to the previous midnight.
Another option is to
group by to_char(created, 'DD.MM.YYYY');
which achieves the same result, but may be slower as it requires a type conversion.
Just pass the list to np.array
:
a = np.array(a)
You can also take this opportunity to set the dtype
if the default is not what you desire.
a = np.array(a, dtype=...)
For me, the combination of Stuart Gathman's and Raviath's answer in this thread did the trick in Windows Server 2016 for iReport 5.6.0.
In addition, I added a symlink within C:\program files\java\jre7 to jdk8 like this:
cmd /c mklink /d "C:\program files\java\jre7\bin" "C:\Program Files\Java\jdk1.8.0_181\bin"
because iReport was constantly complaining that it could not find java.exe within C:\program files\java\jre7\bin\ - So I served it the available java.exe (in my case V8.181) under the desired path and it swallowed it gladly.
Run this command with database name, you want to backup, to take dump of DB.
pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}
eg. pg_dump -U postgres mydbname -f mydbnamedump.sql
Now scp this dump file to remote machine where you want to copy DB.
eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/
On remote machine run following command in ~/some/folder to restore the DB.
psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}
eg. psql -U postgres -d mynewdb -f mydbnamedump.sql
why not use good old PHP? for example, let us say we receive a GET parameter 'target':
function getTarget() {
var targetParam = "<?php echo $_GET['target']; ?>";
//alert(targetParam);
}
Python library authors put the version number in <module>.__version__
. You can print it by running this on the command line:
python -c 'import keras; print(keras.__version__)'
If it's Windows terminal, enclose snippet with double-quotes like below
python -c "import keras; print(keras.__version__)"
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
This is the full text of the blog post linked below:
If you've tried installing a package with pip recently, you may have encountered this error:
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Could not fetch URL https://pypi.python.org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Cannot fetch index base URL https://pypi.python.org/simple/
Could not fetch URL https://pypi.python.org/simple/Django/1.5.1: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/Django/1.5.1 when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1))
No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1))
Storing complete log in /Users/paul/.pip/pip.log
This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work.
The easy workaround for now, is to install pip 1.2.1, which does not require SSL:
curl -O https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
tar xvfz pip-1.2.1.tar.gz
cd pip-1.2.1
python setup.py install
If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.
The most efficient way:
//Note destroys the original string by removing it's last char
// Do not pass in a string literal.
char * getAllButFirstAndLast(char *input)
{
int len = strlen(input);
if(len > 0)
input++;//Go past the first char
if(len > 1)
input[len - 2] = '\0';//Replace the last char with a null termination
return input;
}
//...
//Call it like so
char str[512];
strcpy(str, "hello world");
char *pMod = getAllButFirstAndLast(str);
The safest way:
void getAllButFirstAndLast(const char *input, char *output)
{
int len = strlen(input);
if(len > 0)
strcpy(output, ++input);
if(len > 1)
output[len - 2] = '\0';
}
//...
//Call it like so
char mod[512];
getAllButFirstAndLast("hello world", mod);
The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.
Use the JavaScript RegExp object constructor.
var re = new RegExp("\\w+");
re.test("hello");
You can pass flags as a second string argument to the constructor. See the documentation for details.
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.
ThreadLocals are typically not so widely known as a way to store per-thread state.
Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.
These functions are fairly compact and only use standard Python 2.6 and later.
def ddhhmmss(seconds):
"""Convert seconds to a time string "[[[DD:]HH:]MM:]SS".
"""
dhms = ''
for scale in 86400, 3600, 60:
result, seconds = divmod(seconds, scale)
if dhms != '' or result > 0:
dhms += '{0:02d}:'.format(result)
dhms += '{0:02d}'.format(seconds)
return dhms
def seconds(dhms):
"""Convert a time string "[[[DD:]HH:]MM:]SS" to seconds.
"""
components = [int(i) for i in dhms.split(':')]
pad = 4 - len(components)
if pad < 0:
raise ValueError('Too many components to match [[[DD:]HH:]MM:]SS')
components = [0] * pad + components
return sum(i * j for i, j in zip((86400, 3600, 60, 1), components))
And here are tests to go with them. I'm using the pytest package as a simple way to test exceptions.
import ddhhmmss
import pytest
def test_ddhhmmss():
assert ddhhmmss.ddhhmmss(0) == '00'
assert ddhhmmss.ddhhmmss(2) == '02'
assert ddhhmmss.ddhhmmss(12 * 60) == '12:00'
assert ddhhmmss.ddhhmmss(3600) == '01:00:00'
assert ddhhmmss.ddhhmmss(10 * 86400) == '10:00:00:00'
assert ddhhmmss.ddhhmmss(86400 + 5 * 3600 + 30 * 60 + 1) == '01:05:30:01'
assert ddhhmmss.ddhhmmss(365 * 86400) == '365:00:00:00'
def test_seconds():
assert ddhhmmss.seconds('00') == 0
assert ddhhmmss.seconds('02') == 2
assert ddhhmmss.seconds('12:00') == 12 * 60
assert ddhhmmss.seconds('01:00:00') == 3600
assert ddhhmmss.seconds('1:0:0') == 3600
assert ddhhmmss.seconds('3600') == 3600
assert ddhhmmss.seconds('60:0') == 3600
assert ddhhmmss.seconds('10:00:00:00') == 10 * 86400
assert ddhhmmss.seconds('1:05:30:01') == 86400 + 5 * 3600 + 30 * 60 + 1
assert ddhhmmss.seconds('365:00:00:00') == 365 * 86400
def test_seconds_raises():
with pytest.raises(ValueError):
ddhhmmss.seconds('')
with pytest.raises(ValueError):
ddhhmmss.seconds('foo')
with pytest.raises(ValueError):
ddhhmmss.seconds('1:00:00:00:00')
There are a few packages for prettifying HTML. You can find them by searching the Atom package archive:
Or just go to this link: https://atom.io/packages/search?q=prettify
Once you've selected a package that does what you want you can install it by using the command: apm install [package name]
from the command line or install it using the interface in Preferences.
When the package is installed, follow its instructions for how to activate its capabilities.
You could try following this guide and implement/provide your own MatFormFieldControl
just use this at the end of your button click event
protected void btnAddButton_Click(object sender, EventArgs e)
{
... save data routin
Response.Redirect(Request.Url.AbsoluteUri);
}
You can stablish specific toolbar for div
div::-webkit-scrollbar {
width: 12px;
}
div::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
see demo in jsfiddle.net
When I copied from maven repository, there was 4th row called <type>
.
When I removed this <type>
, it solved my error.
The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
Firebase.remove()
like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:
parent = ref.parent()
parent.on('child_removed', function (snapshot) {
// removed!
})
ref.remove()
According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove
method:
ref.remove(function (error) {
if (!error) {
// removed!
}
}
Find the "Device" section of /etc/X11/xorg.conf
which contains one of the following directives:
Driver "intel"
Driver "radeon"
Driver "fglrx"
And add the following line to that section:
Option "SwapbuffersWait" "false"
And run your application with vblank_mode
environment variable set to 0
:
$ vblank_mode=0 glxgears
$ echo "0/SyncToVBlank=0" >> ~/.nvidia-settings-rc
The same change can be made in the nvidia-settings
GUI by unchecking the option at X Screen 0 / OpenGL Settings / Sync to VBlank
. Or, if you'd like to just test the setting without modifying your ~/.nvidia-settings-rc
file you can do something like:
$ nvidia-settings --load-config-only --assign="SyncToVBlank=0" # disable vertical sync
$ glxgears # test it out
$ nvidia-settings --load-config-only # restore your original vertical sync setting
Validation of viewstate MAC failed. If this application is hosted by a web farm or cluster, ensure that <machineKey>
configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Answer :
<machineKey decryptionKey="2CC8E5C3B1812451A707FBAAAEAC9052E05AE1B858993660" validation="HMACSHA256" decryption="AES" validationKey="CB8860CE588A62A2CF9B0B2F48D2C8C31A6A40F0517268CEBCA431A3177B08FC53D818B82DEDCF015A71A0C4B817EA8FDCA2B3BDD091D89F2EDDFB3C06C0CB32" />
_x000D_
Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
Building on tkerwin's answer, if you happen to have nested parentheses like in
st = "sum((a+b)/(c+d))"
his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d)
, because find searches from the left of the string, and would stop at the first closing parenthesis.
To fix that, you need to use rfind
for the second part of the operation, so it would become
st[st.find("(")+1:st.rfind(")")]