If you are using Hibernate 5.2 and above then you can use this:
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Creating a registry
registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
// Create the MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create the Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
//To shut down
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
As the question is answered. For web develoment. I came so far and found a good explanation about bootsrapping in Laravel doc. Here is the link
In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes.
hope it will help someone who learning web application development.
This should fix it and should be a good habit: .unbind()
$(".addproduct").unbind().click(function(){
//do something
});
There's a jQuery plugin out there called pjax it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."
The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.
What pjax does is that it listens on specified page elements such as <a>
. Then when the <a href=""></a>
element is invoked, the target page is fetched with either the X-PJAX
header, or a specified fragment.
Example:
<script type="text/javascript">
$(document).pjax('a', '#pjax-container');
</script>
Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.
(meaning you want to replace #pjax-container
on the current page with #pjax-container
from the remote page)
When <a>
is invoked, it will fetch the link with the request header X-PJAX
and will look for the contents of #pjax-container
in the result. If the result is #pjax-container
, the container on the current page will be replaced with the new result.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.pjax.js"></script>
<script type="text/javascript">
$(document).pjax('a', '#pjax-container');
</script>
</head>
<body>
<h1>My Site</h1>
<div class="container" id="pjax-container">
Go to <a href="/page2">next page</a>.
</div>
</body>
</html>
If #pjax-container
is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container
.
Example server side code of page2
:
//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
Go to <a href="/page1">next page</a>.
</div>
//else send full page
If you can't change server-side code, then the fragment option is an alternative.
$(document).pjax('a', '#pjax-container', {
fragment: '#pjax-container'
});
Note that fragment
is an older pjax option and appears to fetch the child element of requested element.
If you install newer versions of ionic
globally you can run
ionic cordova resources
and it will generate all of the splashscreen images for you along with the correct sizes.
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
I had the same problem and to solve this I follow this blog article: http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
special tks to @mkyong
You can handle it like this:
for API level 5 and greater
@Override
public void onBackPressed() {
// your code.
}
older than API 5
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code
return true;
}
return super.onKeyDown(keyCode, event);
}
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
Well, those features are specific to a tool that you are using for development in those languages.
You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.
For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html
This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!
protected void Addstaff_Click(object sender, EventArgs e)
{
if (intClassCapcity < intCurrentstaffNumber)
{
MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");
}
else
{
sqlClassList.Insert();
}
}
private void MsgBox(string sMessage)
{
string msg = "<script language=\"javascript\">";
msg += "alert('" + sMessage + "');";
msg += "</script>";
Response.Write(msg);
}
Maybe this can help :)
Controller
$scope.scrollevent = function($e){
// Your code
}
Html
<div scroll scroll-event="scrollevent">//scrollable content</div>
Or
<body scroll scroll-event="scrollevent">//scrollable content</body>
Directive
.directive("scroll", function ($window) {
return {
scope: {
scrollEvent: '&'
},
link : function(scope, element, attrs) {
$("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ? scope.scrollEvent()($e) : null })
}
}
})
The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.
To quote Steve Ouders (CSS optimization expert) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:
Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.
Maintainability of code is much more important in real world scenarios. Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:
Source: http://stevesouders.com/docs/web20expo-20090402.ppt
So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:
<div class="column">
<img class="custom-style" alt="appropriate alt text" />
</div>
This should get you for starting with two letters and ending with two numbers.
[A-Za-z]{2}(.*)[0-9]{2}
If you know it will always be just two and two you can
[A-Za-z]{2}[0-9]{2}
I use it like this:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
The main difference is that WHERE
cannot be used on grouped item (such as SUM(number)
) whereas HAVING
can.
The reason is the WHERE
is done before the grouping and HAVING
is done after the grouping is done.
To answer your question with a working example:
<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = new Array();
for (var index in array[i]) {
line.push('"' + array[i][index] + '"');
}
str += line.join(';');
str += '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>
<div [innerHTML]="HtmlPrint"></div><br>
_x000D_
The innerHtml is a property of HTML-Elements, which allows you to set it’s html-content programatically. There is also a innerText property which defines the content as plain text.
The [attributeName]="value"
box bracket , surrounding the attribute defines an Angular input-binding. That means, that the value of the property (in your case innerHtml) is bound to the given expression, when the expression-result changes, the property value changes too.
So basically [innerHtml]
allows you to bind and dynamically change the html-conent of the given HTML-Element.
if (text[0] == '\0')
{
/* Code... */
}
Use this if you're coding for micro-controllers with little space on flash and/or RAM. You will waste a lot more flash using strlen
than checking the first byte.
The above example is the fastest and less computation is required.
There is a way to convert upper case to lower WITHOUT doing if tests, and it's pretty straight-forward. The isupper() function/macro's use of clocale.h should take care of problems relating to your location, but if not, you can always tweak the UtoL[] to your heart's content.
Given that C's characters are really just 8-bit ints (ignoring the wide character sets for the moment) you can create a 256 byte array holding an alternative set of characters, and in the conversion function use the chars in your string as subscripts into the conversion array.
Instead of a 1-for-1 mapping though, give the upper-case array members the BYTE int values for the lower-case characters. You may find islower() and isupper() useful here.
The code looks like this...
#include <clocale>
static char UtoL[256];
// ----------------------------------------------------------------------------
void InitUtoLMap() {
for (int i = 0; i < sizeof(UtoL); i++) {
if (isupper(i)) {
UtoL[i] = (char)(i + 32);
} else {
UtoL[i] = i;
}
}
}
// ----------------------------------------------------------------------------
char *LowerStr(char *szMyStr) {
char *p = szMyStr;
// do conversion in-place so as not to require a destination buffer
while (*p) { // szMyStr must be null-terminated
*p = UtoL[*p];
p++;
}
return szMyStr;
}
// ----------------------------------------------------------------------------
int main() {
time_t start;
char *Lowered, Upper[128];
InitUtoLMap();
strcpy(Upper, "Every GOOD boy does FINE!");
Lowered = LowerStr(Upper);
return 0;
}
This approach will, at the same time, allow you to remap any other characters you wish to change.
This approach has one huge advantage when running on modern processors, there is no need to do branch prediction as there are no if tests comprising branching. This saves the CPU's branch prediction logic for other loops, and tends to prevent pipeline stalls.
Some here may recognize this approach as the same one used to convert EBCDIC to ASCII.
I would use return null;
to indicate that there is no data to be returned
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary
)
var result = new JsonResult()
{
Data = new
{
partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
}
};
I get what's expected:
{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}
Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult
action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting
Here's a simple actionresult JsonNetResult
http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
You'll see the difference (and can make sure you're using the right one) when serializing a date:
Microsoft way:
{"wireTime":"\/Date(1355627201572)\/"}
JSON.NET way:
{"wireTime":"2012-12-15T19:07:03.5247384-08:00"}
This solved my problem. Add below to your system path
PATH_TO_android\platforms
PATH_TO_android\platform-tools
I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.
For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.
Below is the variable I set in my playbook:
vars:
cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"
That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.
Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
copy(foo,
foo + sizeof(foo) / sizeof(foo[0]),
ostream_iterator<short>(cout, "\n"));
}
This generates the following:
./a.out
1
3
5
7
However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.
Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
reverse_iterator<short *> end(foo);
copy(begin,
end,
ostream_iterator<short>(cout, "\n"));
}
and the output:
$ ./a.out
7
5
3
1
Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
// Generate array iterators using C++14 std::{r}begin()
// and std::{r}end().
// Forward
std::copy(std::begin(foo),
std::end(foo),
std::ostream_iterator<short>(std::cout, "\n"));
// Reverse
std::copy(std::rbegin(foo),
std::rend(foo),
std::ostream_iterator<short>(std::cout, "\n"));
}
If the string is Unicode the easiest way is:
import base64
a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))
# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'
b = base64.b64decode(a).decode("utf-8", "ignore")
print(b)
# b :complex string: ñáéíóúÑ
This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"];
and then set a new value with config.ConnectionString = "your connection string";
. Note that if you have any comments in the connectionStrings
section in Web.Config
these will be removed.
private void UpdateAppSettings(string key, string value)
{
System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
configFile =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
There are also new kids on the block!
If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!
I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).
The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)
In my case i created a separate entity class without the fields that are not required (only with the fields that are required).
Map the entity to the same table. Now when all the columns are required i use the old entity, when only some columns are required, i use the lite entity.
e.g.
@Entity
@Table(name = "user")
Class User{
@Column(name = "id", unique=true, nullable=false)
int id;
@Column(name = "name", nullable=false)
String name;
@Column(name = "address", nullable=false)
Address address;
}
You can create something like :
@Entity
@Table(name = "user")
Class UserLite{
@Column(name = "id", unique=true, nullable=false)
int id;
@Column(name = "name", nullable=false)
String name;
}
This works when you know the columns to fetch (and this is not going to change).
won't work if you need to dynamically decide the columns.
I had the same problem as you.
I did git status
git fetch
git pull
, but my branch was still behind to origin. I had folders and files pushed to remote and I saw the files on the web, but on my local they were missing.
Finally, these commands updated all the files and folders on my local:
git fetch --all
git reset --hard origin/master
or if you want a branch
git checkout your_branch_name_here
git reset --hard origin/your_branch_name_here
The answer by Stephen Katulka (accepted answer) is wrong (the second part).
It explains that Collections.copy(b, a);
does a deep copy, which it does not. Both, new ArrayList(a);
and Collections.copy(b, a);
only do a shallow copy. The difference is, that the constructor allocates new memory, and copy(...)
does not, which makes it suitable in cases where you can reuse arrays, as it has a performance advantage there.
The Java standard API tries to discourage the use of deep copies, as it would be bad if new coders would use this on a regular basis, which may also be one of the reason why clone()
is not public by default.
The source code for Collections.copy(...)
can be seen on line 552 at:
http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Core/Collections-Jar-Zip-Logging-regex/java/util/Collections.java.htm
If you need a deep copy, you have to iterate over the items manually, using a for loop and clone() on each object.
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m
Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini
file which is present in your Eclipse home directory.
To get the size of the JVM during Runtime you can use Runtime.totalMemory()
which returns the total amount of memory in the Java virtual machine, measured in bytes.
When I ran taskkill to stop the javaw.exe process it would say it had terminated but remained running. The jqs process (java qucikstart) needs to be stopped also. Running this batch file took care of the issue.
taskkill /f /im jqs.exe
taskkill /f /im javaw.exe
taskkill /f /im java.exe
Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.
There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request
in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:
import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text)
some_elements = soup.find_all("div", class_="myCssClass")
Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.
When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:
from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)
I would advice to start your own solution. You'll understand Scrapy's benefits doing so.
ps: take a look at scrapely: https://github.com/scrapy/scrapely
pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia
Try to modify your eclipse.ini with below
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Dhelp.lucene.tokenizer=standard
-Xms2G
-Xmx3G
-XX:MaxPermSize=2G
-XX:+UseCompressedOops
-XX:+UseParallelGC
Once you open your eclipse you can try below
Looks like your application consumes more memory than allocated (Default). I will try two things
As suggested by Harmlezz increase your memory allocation to JVM to -Xms2g -Xmx2g (If needed increase it more and try it out)
Download eclipse memory analyzer and check for what causing memory leak OR even you can use JConsole to see JVM memory utilization in order to figure out application memory leak issue.
The other answers here cover this well, but it is worth knowing that there is built in functionality for splash screens in Visual Studio: If you open the project properties for the windows form app and look at the Application tab, there is a "Splash screen:" option at the bottom. You simply pick which form in your app you want to display as the splash screen and it will take care of showing it when the app starts and hiding it once your main form is displayed.
You still need to set up your form as described above (with the correct borders, positioning, sizing etc.)
Try this:
In the IIS Manager right click on Web sites, chose New, then Web site...
This way you can recreate the Default Web Site.
After these steps restart IIS: Right click on local computer, All Tasks, Restart IIS...
You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3)
. If you get an error, you don't have the right version.
For example, DATETIME(3)
will give you millisecond resolution in your timestamps, and TIMESTAMP(6)
will give you microsecond resolution on a *nix-style timestamp.
Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html
NOW(3)
will give you the present time from your MySQL server's operating system with millisecond precision.
If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value
FROM_UNIXTIME(ms * 0.001)
Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.
(Notice that MySQL internal fractional arithmetic, like * 0.001
, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)
If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.
If, for some reason you can't upgrade, you could consider using BIGINT
or DOUBLE
columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001)
will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000
You can do this without a JOIN
:
SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
FROM YourTable
)sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids
Demo: SQL Fiddle
Inside <td>
, use style="border-left:1px solid #colour;"
VBA stands for Visual Basic for Applications and so is the small "for applications" scripting brother of VB. VBA is indeed available in Excel, but also in the other office applications.
With VB, one can create a stand-alone windows application, which is not possible with VBA.
It is possible for developers however to "embed" VBA in their own applications, as a scripting language to automate those applications.
Edit: From the VBA FAQ:
Q. What is Visual Basic for Applications?
A. Microsoft Visual Basic for Applications (VBA) is an embeddable programming environment designed to enable developers to build custom solutions using the full power of Microsoft Visual Basic. Developers using applications that host VBA can automate and extend the application functionality, shortening the development cycle of custom business solutions.
Note that VB.NET is even another language, which only shares syntax with VB.
TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);
I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
I had exactly this problem a couple of months ago while working on a WYSIWYG email editor for my company. Outlook only supports background images if they're applied to the <body>
tag - any other element and it'll fail.
In the end, the only workaround I found was to use <div>
element for text input, then during the content submission process I fired an AJAX request with the <div>
's content to a PHP script which wrote the text onto a blank version of our header image, saved the file and returned its (uniquely generated) name. I then used Javascript to remove the <div>
and add an <img>
tag using the returned filename in the src
attribute.
You can get all the info/methodology from the imagecreatefrompng()
page on the PHP Docs site.
What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
This will print it in the following format
10 23 42
1 654 0
40652 22 0
if you want more exact formatting you'll have to change how the printf is formatted.
Yes, there are no classes built into .NET to edit query strings. You'll have to either use Regex or some other method of altering the string itself.
Yet another answer ... If you land here in Oct 2020 because PHP on the command line (CLI) has stopped working, guess what ... some upgrades will move you to a different/newer version of PHP silently, without asking!
Run:
php --version
and you might be surprised to see what version the CLI is running.
Then run:
ll /usr/bin/php
and you might be surprised to see where this is linking to.
It's best to reference the SPECIFIC version of PHP you want when calling the PHP binary directly and not a symbolic link.
Example:
/usr/bin/php7.3
will give you the exact version you want. You can't trust /usr/bin/php or even just typing php because an upgrade might switch versions on you silently.
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
@foreach($datas as $student)
{{$student}}
@endforeach
[Link here]
As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?
Here are few ways to do it:
Imagine we have this array in your code:
var arr = [1, 2, 3, 4, 5];
1) Looping through the array in a function and return a new array, like this:
function newArr(arr) {
var i=0, res = [];
while(i<arr.length){
res.push(arr[i]);
i++;
}
return res;
}
2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:
var arr2 = arr.slice(); // make a copy of the original array
3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:
var arr2 = arr.concat();
4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:
var arr2 = JSON.parse(JSON.stringify(arr));
5) Array.from method, this is not widely supported, before use check the support in different browsers:
const arr2 = Array.from(arr);
6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:
const arr2 = [...arr];
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
You'll want a Map<String, String>
. Classes that implement the Map
interface include (but are not limited to):
Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap
is probably the most common; the go-to default.
For example (using a HashMap
):
Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal
I found this worked in my scenario.
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
$.get("urlToCheck.com").done(function () {
alert("success");
}).fail(function () {
alert("failed.");
});
I'm not familiar with paramiko, but this may work:
ssh_stdin.write('input value')
ssh_stdin.flush()
For information on stdin:
http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
A great book on REST is REST in Practice.
Must reads are Representational State Transfer (REST) and REST APIs must be hypertext-driven
See Martin Fowlers article the Richardson Maturity Model (RMM) for an explanation on what an RESTful service is.
To be RESTful a Service needs to fulfill the Hypermedia as the Engine of Application State. (HATEOAS), that is, it needs to reach level 3 in the RMM, read the article for details or the slides from the qcon talk.
The HATEOAS constraint is an acronym for Hypermedia as the Engine of Application State. This principle is the key differentiator between a REST and most other forms of client server system.
...
A client of a RESTful application need only know a single fixed URL to access it. All future actions should be discoverable dynamically from hypermedia links included in the representations of the resources that are returned from that URL. Standardized media types are also expected to be understood by any client that might use a RESTful API. (From Wikipedia, the free encyclopedia)
REST Litmus Test for Web Frameworks is a similar maturity test for web frameworks.
Approaching pure REST: Learning to love HATEOAS is a good collection of links.
REST versus SOAP for the Public Cloud discusses the current levels of REST usage.
REST and versioning discusses Extensibility, Versioning, Evolvability, etc. through Modifiability
I came across this great blog/tutorial/whatever about dealing with case sensitive pattern. The following three methods are explained in details with examples:
1. Convert pattern to lowercase using tr command
opt=$( tr '[:upper:]' '[:lower:]' <<<"$1" )
case $opt in
sql)
echo "Running mysql backup using mysqldump tool..."
;;
sync)
echo "Running backup using rsync tool..."
;;
tar)
echo "Running tape backup using tar tool..."
;;
*)
echo "Other options"
;;
esac
2. Use careful globbing with case patterns
opt=$1
case $opt in
[Ss][Qq][Ll])
echo "Running mysql backup using mysqldump tool..."
;;
[Ss][Yy][Nn][Cc])
echo "Running backup using rsync tool..."
;;
[Tt][Aa][Rr])
echo "Running tape backup using tar tool..."
;;
*)
echo "Other option"
;;
esac
3. Turn on nocasematch
opt=$1
shopt -s nocasematch
case $opt in
sql)
echo "Running mysql backup using mysqldump tool..."
;;
sync)
echo "Running backup using rsync tool..."
;;
tar)
echo "Running tape backup using tar tool..."
;;
*)
echo "Other option"
;;
esac
shopt -u nocasematch
There is another one way, in which you can get indexPath of the cell where your button was pressed:
using usual action selector like:
UIButton *btn = ....;
[btn addTarget:self action:@selector(yourFunction:) forControlEvents:UIControlEventTouchUpInside];
and then in in yourFunction:
- (void) yourFunction:(id)sender {
UIButton *button = sender;
CGPoint center = button.center;
CGPoint rootViewPoint = [button.superview convertPoint:center toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
//the rest of your code goes here
..
}
since you get an indexPath it becames much simplier.
You can use numpy.logical_not
to invert the boolean array returned by isin
:
In [63]: s = pd.Series(np.arange(10.0))
In [64]: x = range(4, 8)
In [65]: mask = np.logical_not(s.isin(x))
In [66]: s[mask]
Out[66]:
0 0
1 1
2 2
3 3
8 8
9 9
As given in the comment by Wes McKinney you can also use
s[~s.isin(x)]
Hadley's tidyr
just got this amazing function drop_na
library(tidyr)
DF %>% drop_na(y)
x y z
1 1 0 NA
2 2 10 33
Solution using str_pad:
str_pad($digit,2,'0',STR_PAD_LEFT);
Benchmark on php 5.3
Result str_pad : 0.286863088608
Result sprintf : 0.234171152115
Code:
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
str_pad(9,2,'0',STR_PAD_LEFT);
str_pad(15,2,'0',STR_PAD_LEFT);
str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
sprintf("%02d", 9);
sprintf("%02d", 15);
sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";
I had installed CUDA 10.1 and CUDNN 7.6 by mistake. You can use following configurations (This worked for me - as of 9/10). :
But I had to create symlinks for it to work as tensorflow originally works with CUDA 10.
sudo ln -s /opt/cuda/targets/x86_64-linux/lib/libcublas.so /opt/cuda/targets/x86_64-linux/lib/libcublas.so.10.0
sudo cp /usr/lib/x86_64-linux-gnu/libcublas.so.10 /usr/local/cuda-10.1/lib64/
sudo ln -s /usr/local/cuda-10.1/lib64/libcublas.so.10 /usr/local/cuda-10.1/lib64/libcublas.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusolver.so.10 /usr/local/cuda/lib64/libcusolver.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcurand.so.10 /usr/local/cuda/lib64/libcurand.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcufft.so.10 /usr/local/cuda/lib64/libcufft.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcudart.so /usr/local/cuda/lib64/libcudart.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusparse.so.10 /usr/local/cuda/lib64/libcusparse.so.10.0
And add the following to my ~/.bashrc -
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
export PATH=/usr/local/cuda-10.1/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/cuda/targets/x86_64-linux/lib/
import traceback
traceback.print_stack()
The class attribute can contain multiple styles, so you could specify it as
<tr class="row-even highlight">
and do string manipulation to remove 'highlight' from element.className
element.className=element.className.replace('hightlight','');
Using jQuery would make this simpler as you have the methods
$("#id").addClass("highlight");
$("#id").removeClass("hightlight");
that would enable you to toggle highlighting easily
I use this solution:
It's a bit more concise since I use: ng-repeat="obj in objects | filter : paginate"
to filter the rows. Also made it working with $resource:
$http({
method: 'GET',
url:'/http://localhost:8080/example/test' + toto,
data: '',
headers: {
'Content-Type': 'application/json'
}
}).then(
function(response) {
return response.data;
},
function(errResponse) {
console.error('Error !!');
return $q.reject(errResponse);
}
Successfully Script for your question ,Full Test
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<p title="text" id="FileNameShow" ></p>
<input type="file"
id="myfile"
onchange="javascript:showSrc();"
size="30">
<script type="text/javascript">
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'), with_this);
}
function showSrc() {
document.getElementById("myframe").href = document.getElementById("myfile").value;
var theexa = document.getElementById("myframe").href.replace("file:///", "");
var path = document.getElementById("myframe").href.replace("file:///", "");
var correctPath = replaceAll(path, "%20", " ");
alert(correctPath);
var filename = correctPath.replace(/^.*[\\\/]/, '')
$("#FileNameShow").text(filename)
}
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
Joey mentioned that Format-*
is for human consumption. If you're writing to a file for machine consumption, maybe you want to use Export-*
? Some good ones are
Export-Csv
- Comma separated value. Great for when you know what the columns are going to beExport-Clixml
- You can export whole objects and collections. This is great for serialization.If you want to read back in, you can use Import-Csv
and Import-Clixml
. I find that I like this better than inventing my own data formats (also it's pretty easy to whip up an Import-Ini
if that's your preference).
Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).
nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)
should work.
6 years late to the party but I've been searching for how to extract an html element's tag attribute value, so for:
<span property="addressLocality">Ayr</span>
I want "addressLocality". I kept being directed back here, but the answers didn't really solve my problem.
How I managed to do it eventually:
>>> from bs4 import BeautifulSoup as bs
>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}
As it's a dict, you can then also use keys
and 'values'
>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']
Hopefully it helps someone else!
You can do somthing like :
if (product != null) {
var products = Repository.Products;
var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
Repository.Products[indexOf] = product;
// or
Repository.Products[indexOf].prop = product.prop;
}
<p id="checkAll">Check All</p>
<hr />
<input type="checkbox" class="checkItem">Item 1
<input type="checkbox" class="checkItem">Item 2
<input type="checkbox" class="checkItem">Item3
And jquery
$(document).on('click','#checkAll',function () {
$('.checkItem').not(this).prop('checked', this.checked);
});
$(selector).filter(function(){return this.value==yourval}).remove();
RazorSQL for Linux / Unix.
I had the same problem with Versions displaying the same message. I simply right clicked the offending files and selected 'Revert...' from the right-click menu and all was good.
Basically Versions (actually Subversion) thinks you still want to add the file, but it cannot find it because you deleted it in the file system. The Revert option tells Subversion to forget about adding it.
If you need the values of i and j, this should work but with less performance than others
for(i;i< 1000; i++){
for(j; j< 1000; j++){
if(condition)
break;
}
if(condition) //the same condition
break;
}
while Alexey Kukanov's answer may be more efficient, you can also iterate through a queue in a very natural manner, by popping each element from the front of the queue, then pushing it to the back:
#include <iostream>
#include <queue>
using namespace std;
int main() {
//populate queue
queue<int> q;
for (int i = 0; i < 10; ++i) q.push(i);
// iterate through queue
for (size_t i = 0; i < q.size(); ++i) {
int elem = std::move(q.front());
q.pop();
elem *= elem;
q.push(std::move(elem));
}
//print queue
while (!q.empty()) {
cout << q.front() << ' ';
q.pop();
}
}
output:
0 1 4 9 16 25 36 49 64 81
The Apache docs recommend against using a rewrite:
To redirect
http
URLs tohttps
, do the following:<VirtualHost *:80> ServerName www.example.com Redirect / https://www.example.com/ </VirtualHost> <VirtualHost *:443> ServerName www.example.com # ... SSL configuration goes here </VirtualHost>
This snippet should go into main server configuration file, not into .htaccess
as asked in the question.
This article might have come up only after the question was asked and answered, but seems to be the current way to go.
just use this attribute
[System.Web.Http.HttpGet]
not need this line of code:
[System.Web.Http.AcceptVerbs("GET", "POST")]
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id'); // you can add here your personal ID
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data : {
action : 'my_action',
userID : userID
},
success: function(data)
{
alert("success!");
console.log(data);
}
});
});
});
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
echo $uid;
$uid add in your functions
note: if $ is not supperted than add jQuery where $ defined
With the devel version of tidyr
‘0.8.3.9000’
, there is pivot_wider
and pivot_longer
which is generalized to do the reshaping (long -> wide, wide -> long, respectively) from 1 to multiple columns. Using the OP's data
-single column long -> wide
library(dplyr)
library(tidyr)
dat1 %>%
pivot_wider(names_from = numbers, values_from = value)
# A tibble: 2 x 5
# name `1` `2` `3` `4`
# <fct> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746
#2 secondName -0.898 -0.335 -0.501 -0.175
-> created another column for showing the functionality
dat1 %>%
mutate(value2 = value * 2) %>%
pivot_wider(names_from = numbers, values_from = c("value", "value2"))
# A tibble: 2 x 9
# name value_1 value_2 value_3 value_4 value2_1 value2_2 value2_3 value2_4
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746 0.682 -1.41 -0.759 -1.49
#2 secondName -0.898 -0.335 -0.501 -0.175 -1.80 -0.670 -1.00 -0.349
The following will give you the size of the browsers viewport.
$(window).height(); // returns height of browser viewport
$(window).width(); // returns width of browser viewport
LCASE or UCASE respectively.
Example:
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
curl -H "Content-Type: text/xml; charset=utf-8" \
-H "SOAPAction:" \
-d @soap.txt -X POST http://someurl
I have got this error only when debugging the ASP .Net Application.
I also had Session["mysession"]
kind of variables added into my Watch of Visual Studio.
the issue was solved Once, I have removed the Session Variables from watch.
** Used table to align the radio and text in one line
<div >_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td><strong>Do you want to add new server ?</strong></td>_x000D_
<td><input type="radio" name="addServer" id="serverYes" value="1"></td>_x000D_
<td>Yes</td>_x000D_
<td><input type="radio" name="addServer" id="serverNo" value="1"></td>_x000D_
<td>No</td>_x000D_
_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
**
I think using the matrix.at<type>(x,y)
is not the best way to iterate trough a Mat object!
If I recall correctly matrix.at<type>(x,y)
will iterate from the beginning of the matrix each time you call it(I might be wrong though).
I would suggest using cv::MatIterator_
cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
std::cout << *_it << std::endl;
}
May be You are using pgadmin by connecting remote host then U are trying to update there from your system but it searches for that file in remote system's file system... its the error wat I faced May be its also for u check it
Try this:
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down'
I ran into the same issue after upgrading Git. Turns out I switched from 32-bit to 64-bit Git and I didn't realize it. TortoiseGit was still looking for "C:\Program Files (x86)\Git\bin", which didn't exist. Right-click the folder, go to Tortoise Git > Settings > General and update the Git.exe path.
The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:
First of all: it is very unfortunate and surprising that R cannot draw error bars "out of the box".
Here is my favourite workaround, the advantage is that you do not need any extra packages. The trick is to draw arrows (!) but with little horizontal bars instead of arrowheads (!!!). This not-so-straightforward idea comes from the R Wiki Tips and is reproduced here as a worked-out example.
Let's assume you have a vector of "average values" avg
and another vector of "standard deviations" sdev
, they are of the same length n
. Let's make the abscissa just the number of these "measurements", so x <- 1:n
. Using these, here come the plotting commands:
plot(x, avg,
ylim=range(c(avg-sdev, avg+sdev)),
pch=19, xlab="Measurements", ylab="Mean +/- SD",
main="Scatter plot with std.dev error bars"
)
# hack: we draw arrows but with very special "arrowheads"
arrows(x, avg-sdev, x, avg+sdev, length=0.05, angle=90, code=3)
The result looks like this:
In the arrows(...)
function length=0.05
is the size of the "arrowhead" in inches, angle=90
specifies that the "arrowhead" is perpendicular to the shaft of the arrow, and the particularly intuitive code=3
parameter specifies that we want to draw an arrowhead on both ends of the arrow.
For horizontal error bars the following changes are necessary, assuming that the sdev
vector now contains the errors in the x
values and the y
values are the ordinates:
plot(x, y,
xlim=range(c(x-sdev, x+sdev)),
pch=19,...)
# horizontal error bars
arrows(x-sdev, y, x+sdev, y, length=0.05, angle=90, code=3)
This can help you
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
HTML
<div class="row">
<div class="col-xs-2 pull-bottom"
style="height:100px;background:blue">
</div>
<div class="col-xs-8 pull-bottom"
style="height:50px;background:yellow">
</div>
</div>
CSS
.pull-bottom {
display: inline-block;
vertical-align: bottom;
float: none;
}
I wanted the date to be shown in the type='time' field.
The normal conversion skips the zeros and the form field does not show the value and puts forth an error in the console saying the format needs to be yyyy-mm-dd.
Hence I added a small statement (check)?(true):(false) as follows:
makeShortDate=(date)=>{
yy=date.getFullYear()
mm=date.getMonth()
dd=date.getDate()
shortDate=`${yy}-${(mm<10)?0:''}${mm+1}-${(dd<10)?0:''}${dd}`;
return shortDate;
}
Here's an example where I found the replace( ) function helpful for giving me insight. The problem required a long integer vector be changed into a character vector and with its integers replaced by given character values.
## figuring out replace( )
(test <- c(rep(1,3),rep(2,2),rep(3,1)))
which looks like
[1] 1 1 1 2 2 3
and I want to replace every 1 with an A and 2 with a B and 3 with a C
letts <- c("A","B","C")
so in my own secret little "dirty-verse" I used a loop
for(i in 1:3)
{test <- replace(test,test==i,letts[i])}
which did what I wanted
test
[1] "A" "A" "A" "B" "B" "C"
In the first sentence I purposefully left out that the real objective was to make the big vector of integers a factor vector and assign the integer values (levels) some names (labels).
So another way of doing the replace( ) application here would be
(test <- factor(test,labels=letts))
[1] A A A B B C
Levels: A B C
The main problem with the validated answer is you'll have to parse the output to get the informations. Here is a query allowing you to get them in a more usable manner :
SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
links.TABLE_NAME, links.COLUMN_NAME,
cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
AND refs.TABLE_NAME=cols.TABLE_NAME
AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
AND cols.TABLE_NAME="table"
You can try this way:-
Give a class say header
to the header rows, use nextUntil to get all rows beneath the clicked header until the next header.
$('.header').click(function(){
$(this).nextUntil('tr.header').slideToggle(1000);
});
<table border="0">
<tr class="header">
<td colspan="2">Header</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
Another Example:
$('.header').click(function(){
$(this).find('span').text(function(_, value){return value=='-'?'+':'-'});
$(this).nextUntil('tr.header').slideToggle(100); // or just use "toggle()"
});
You can also use promise to toggle the span icon/text after the toggle is complete in-case of animated toggle.
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
$this.find('span').text(function (_, value) {
return value == '-' ? '+' : '-'
});
});
});
Or just with a css pseudo element to represent the sign of expansion/collapse, and just toggle a class on the header.
CSS:-
.header .sign:after{
content:"+";
display:inline-block;
}
.header.expand .sign:after{
content:"-";
}
JS:-
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
Request.QueryString["pID"];
Here Request is a object that retrieves the values that the client browser passed to the server during an HTTP request and QueryString is a collection is used to retrieve the variable values in the HTTP query string.
READ MORE@ http://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx
according to documentation you should just
{ path: '**', component: DefaultLayoutComponent }
on your app-routing.module.ts source: https://angular.io/guide/router
Laravel 5 gets its enviroment related variables from the .env
file located in the root of your project. You just need to set APP_ENV
to whatever you want, for example:
APP_ENV=development
This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:
APP_DEBUG=true
The role of the .env
file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env
file settings would be different from your local development enviroment.
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.
Just as a normal js object:
let myhash: IHash = {};
myhash["somestring"] = "value"; //set
let value = myhash["somestring"]; //get
There are two things you're doing with [indexer: string] : string
You can make a general dictionary with explicitly typed fields by using [key: string]: any;
e.g. age
must be number
, while name
must be a string - both are required. Any implicit field can be any type of value.
As an alternative, there is a Map
class:
let map = new Map<object, string>();
let key = new Object();
map.set(key, "value");
map.get(key); // return "value"
This allows you have any Object instance (not just number/string) as the key.
Although its relatively new so you may have to polyfill it if you target old systems.
If you're not using jQuery... you need to access one of the event's TouchList
s to get a Touch
object which has pageX/Y
clientX/Y
etc.
Here are links to the relevant docs:
I'm using e.targetTouches[0].pageX
in my case.
@maxisam thanks for ngx-window-token. I was doing something similar but switched to yours. This is my service for listening to window resize events and notifying subscribers.
import { Inject, Injectable } from '@angular/core';_x000D_
import { BehaviorSubject } from 'rxjs/BehaviorSubject';_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/observable/fromEvent';_x000D_
import { WINDOW } from 'ngx-window-token';_x000D_
_x000D_
_x000D_
export interface WindowSize {_x000D_
readonly width: number;_x000D_
readonly height: number;_x000D_
}_x000D_
_x000D_
@Injectable()_x000D_
export class WindowSizeService {_x000D_
_x000D_
constructor( @Inject(WINDOW) private _window: any ) {_x000D_
Observable.fromEvent(_window, 'resize')_x000D_
.auditTime(100)_x000D_
.map(event => <WindowSize>{width: event['currentTarget'].innerWidth, height: event['currentTarget'].innerHeight})_x000D_
.subscribe((windowSize) => {_x000D_
this.windowSizeChanged$.next(windowSize);_x000D_
});_x000D_
}_x000D_
_x000D_
readonly windowSizeChanged$ = new BehaviorSubject<WindowSize>(<WindowSize>{width: this._window.innerWidth, height: this._window.innerHeight});_x000D_
}
_x000D_
Short and sweet and works like a charm.
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
I use the environment variable CDPATH
I would use
waitForElementPresent(locator)
This will wait until the element is present in the DOM.
If you need to check the element is visible, you may be better using
waitForElementHeight(locator)
10 years later but that problem still caught me.
So this is the answer to those that are too late as me.
This does not work
int b = (int) Math.ceil(a / 100);
Cause the result a / 100
turns out to be an integer and it's rounded so Math.ceil
can't do anything about it.
You have to avoid the rounded operation with this
int b = (int) Math.ceil((float) a / 100);
Now it works.
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
You can turn autocommit ON by setting implicit_transactions OFF:
SET IMPLICIT_TRANSACTIONS OFF
When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.
Maybe an example is clearer. This will write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION
This will not write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
The following example will update a row, and then complain that there's no transaction to commit:
SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.
public FileContentResult GetImage(int productId) {
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
This is an old post however, one alternative is to use the command options:
ftp -n -s:ftpcmd.txt
the -n will suppress the initial login and then the file contents would be: (replace the 127.0.0.1 with your FTP site url)
open 127.0.0.1
user myFTPuser myftppassword
other commands here...
This avoids the user/password on separate lines
To hide those warnings, you could do this before your actual code.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
I have a solution that's similar to ironhacker's except that I use logging.exception in some of my code and found that I needed to format the exception before passing it back over the Queue since tracebacks aren't pickle'able:
class QueueHandler(logging.Handler):
def __init__(self, queue):
logging.Handler.__init__(self)
self.queue = queue
def emit(self, record):
if record.exc_info:
# can't pass exc_info across processes so just format now
record.exc_text = self.formatException(record.exc_info)
record.exc_info = None
self.queue.put(record)
def formatException(self, ei):
sio = cStringIO.StringIO()
traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
s = sio.getvalue()
sio.close()
if s[-1] == "\n":
s = s[:-1]
return s
None of the proposed answers completely worked for me. My use case is slightly different (doing an ajax get to an S3 .json file in IE9). Setting jQuery.support.cors = true;
got rid of the No Transport
error but I was still getting Permission denied
errors.
What did work for me was to use the jQuery-ajaxTransport-XDomainRequest to force IE9 to use XDomainRequest. Using this did not require setting jQuery.support.cors = true;
If you call this function then you easily get the client's IP address. I have already used this in my existing project:
public function getUserIpAddr(){
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
A compiler may place structure members on particular byte boundaries for reasons of performance on a particular architecture. This may leave unused padding between members. Structure packing forces members to be contiguous.
This may be important for example if you require a structure to conform to a particular file or communications format where the data you need the data to be at specific positions within a sequence. However such usage does not deal with endian-ness issues, so although used, it may not be portable.
It may also to exactly overlay the internal register structure of some I/O device such as a UART or USB controller for example, in order that register access be through a structure rather than direct addresses.
For uploading, the S3 SDK has two putObject methods:
PutObjectRequest(String bucketName, String key, File file)
and
PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata)
The inputstream+ObjectMetadata method needs a minimum metadata of Content Length of your inputstream. If you don't, then it will buffer in-memory to get that information, this could cause OOM. Alternatively, you could do your own in-memory buffering to get the length, but then you need to get a second inputstream.
Not asked by the OP (limitations of his environment), but for someone else, such as me. I find it easier, and safer (if you have access to temp file), to write the inputstream to a temp file, and put the temp file. No in-memory buffer, and no requirement to create a second inputstream.
AmazonS3 s3Service = new AmazonS3Client(awsCredentials);
File scratchFile = File.createTempFile("prefix", "suffix");
try {
FileUtils.copyInputStreamToFile(inputStream, scratchFile);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, id, scratchFile);
PutObjectResult putObjectResult = s3Service.putObject(putObjectRequest);
} finally {
if(scratchFile.exists()) {
scratchFile.delete();
}
}
try this:
TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+" line2" );
Just to keep this subject complete, I found a solution not explored Here using Fixed position.
html, body, .wrapper, .parent, .child {_x000D_
position: fixed;_x000D_
top: 0; _x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
overflow: auto;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.height-50 {_x000D_
height: 50%;_x000D_
width: 5em;_x000D_
margin: 10px auto;_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
_x000D_
<div class="height-50"></div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
html, body, .wrapper, .parent, .child {_x000D_
position: fixed;_x000D_
top: 0; _x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
overflow: auto;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.height-150 {_x000D_
height: 150%;_x000D_
width: 5em;_x000D_
margin: 10px auto;_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
_x000D_
<div class="height-150"></div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You should use this.state.check
instead of check.value
here:
this.setState({check: !this.state.check})
But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.
malloc()
and calloc()
are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.
Their prototypes are as follows:
void *malloc( size_t n);
void *calloc( size_t n, size_t t)
There are mainly two differences between the two:
Behavior: malloc()
allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc()
, on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.
Syntax: malloc()
takes 1 argument (the size to be allocated), and calloc()
takes two arguments (number of blocks to be allocated and size of each block).
The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.
Example:
int *arr;
// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int));
// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));
The same functionality as calloc()
can be achieved using malloc()
and memset()
:
// allocate memory for 10 integers with garbage values
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int));
Note that malloc()
is preferably used over calloc()
since it's faster. If zero-initializing the values is wanted, use calloc()
instead.
Unfortunately, what you want is not possible with Python (which makes Python close to useless for command-line one-liner programs). Even explicit use of parentheses does not avoid the syntax exception. You can get away with a sequence of simple statements, separated by semi-colon:
for i in range(10): print "foo"; print "bar"
But as soon as you add a construct that introduces an indented block (like if
), you need the line break. Also,
for i in range(10): print "i equals 9" if i==9 else None
is legal and might approximate what you want.
As for the try ... except
thing: It would be totally useless without the except
. try
says "I want to run this code, but it might throw an exception". If you don't care about the exception, leave away the try
. But as soon as you put it in, you're saying "I want to handle a potential exception". The pass
then says you wish to not handle it specifically. But that means your code will continue running, which it wouldn't otherwise.
You can use the
re
library
Assuming that you are able to load your full txt-file. You then define a list of unwanted nicknames and then substitute them with an empty string "".
# Delete unwanted characters
import re
# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
Not sure if this is relevant but I had the same problem with Fiddler after the last update (v2.4.5.0). I turned all filters off but still wasn't picking up any traffic. When I unchecked Use Filters on the filters tab, however, all traffic was picked up as normal. I'm still trying to figure out how I can use filters when just checking Use Filters box causes all traffic to be blocked.
I recommend using ECMAScript 6 spread operator, which will Bind trailing parameters to an array. With this solution you don't need to touch the arguments
object and your code will be simplified. The downside of this solution is that it does not work across most browsers, so instead you will have to use a JS compiler such as Babel. Under the hood Babel transforms arguments
into a Array with a for loop.
function sortArgs(...args) {
return args.sort();
}
If you can not use a ECMAScript 6, I recommend looking at some of the other answers such as @Jonathan Fingland
function sortArgs() {
var args = Array.prototype.slice.call(arguments);
return args.sort();
}
By default, SQL statements are terminated with semicolons. You use a semicolon to terminate statements unless you've (rarely) set a new statement terminator.
If you're sending just one statement, technically you can dispense with the statement terminator; in a script, as you're sending more than one statement, you need it.
In practice, always include the terminator even if you're just sending one statement to the database.
Edit: in response to those saying statement terminators are not required by [particular RDBMS], while that may be true, they're required by the ANSI SQL Standard. In all programming, if we can adhere to a Standard without loss of functionality, we should, because then neither our code or our habits are tied to one proprietary vendor.
With some C compilers, it's possible to have main return void, even though the Standard requires main to return int. But doing so makes our code, and ourselves, less portable.
The biggest difficulty in programming effectively isn't learning new things, it's unlearning bad habits. To the extent that we can avoid acquiring bad habits in the first place, it's a win for us, for our code, and for anyone reading or using our code.
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
Seems like the problem is with the date format.
var d = "17-09-2013 10:08",
dArr = d.split('-'),
ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000
There's are multiple ways to split a string :
_
import net package
host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
Split based on struct :
_
type ServerDetail struct {
Host string
Port string
err error
}
ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port
Now use in you code like ServerDetail.Host
and ServerDetail.Port
If you don't want to split specific string do it like this:
type ServerDetail struct {
Host string
Port string
}
ServerDetail = strings.Split([Your_String], ":") // Common split method
and use like ServerDetail.Host
and ServerDetail.Port
.
That's All.
Use the PasteSpecial method:
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).
What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.
It gives you neat drag and drop controls onto your service but... don't even try deploying it. Won't work.
Services: Only use System.Timers.Timer System.Windows.Forms.Timer won't work even though it's available in the toolbox
Services: BackgroundWorkers will not work when it's running as a service Use System.Threading.ThreadPools instead or Async calls
Java 8 supports default methods in interfaces. And in JDK 8 a lot of old interfaces now have new default methods. For example, now in CharSequence we have chars and codePoints methods.
If source level of your project is lower than 1.8, then compiler doesn't allow you to use default methods in interfaces. So it cannot compile classes that directly on indirectly depend on this interfaces.
If I get your problem right, then you have two solutions. First solution is to rollback to JDK 7, then you will use old CharSequence interface without default methods. Second solution is to set source level of your project to 1.8, then your compiler will not complain about default methods in interfaces.
There are more than a few gateways out there, but I am not aware of a reliable gateway that is free. Most gateways like PayPal will provide you APIs that will allow you to process credit cards, as well as do things like void, charge, or refund.
The other thing you need to worry about is the coming of PCI compliance which basically says if you are not compliant, you (or the company you work for) will be liable by your Merchant Bank and/or Card Vendor for not being compliant by July of 2010. This will impose large fines on you and possibly revoke the ability for you to process credit cards.
All that being said companies like PayPal have a PHP SDK:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks
Authorize.Net:
http://developer.authorize.net/samplecode/
Those are two of the more popular ones for the United States.
For PCI Info see:
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
https://developers.google.com/chrome-developer-tools/docs/settings
The current version of dialog has the option "dialogClass" which you can use with your id's. For example,
$('foo').dialog({dialogClass:'dialog_style1'});
Then the CSS would be
.dialog_style1 {color:#aaa;}
There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.
Let's consider that we are troubleshooting the following line:
require "/path/to/file"
or move whatever is called by require*
or include*
to its own variable, echo it, copy it, and try accessing it from a terminal:
$path = "/path/to/file";
echo "Path : $path";
require "$path";
Then, in a terminal:
cat <file path pasted>
/users/tony/htdocs
Best practices :
In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :
require __DIR__ . "/relative/path/from/current/file"
. The __DIR__
magic constant returns the directory of the current file.define a SITE_ROOT
constant yourself :
config.php
in config.php
, write
define('SITE_ROOT', __DIR__);
in every file where you want to reference the site root folder, include config.php
, and then use the SITE_ROOT
constant wherever you like :
require_once __DIR__."/../config.php";
...
require_once SITE_ROOT."/other/file.php";
These 2 practices also make your application more portable because it does not rely on ini settings like the include path.
Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.
Such an inclusion will look like this :
include "Zend/Mail/Protocol/Imap.php"
In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.
You can check the include path with :
echo get_include_path();
You can add a folder to it with :
set_include_path(get_include_path().":"."/path/to/new/folder");
It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.
To check under what user the server is running you can use posix_getpwuid :
$user = posix_getpwuid(posix_geteuid());
var_dump($user);
To find out the permissions on the file, type the following command in the terminal:
ls -l <path/to/file>
and look at permission symbolic notation
If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.
Three settings could be relevant :
phpinfo()
or by using ini_get("open_basedir")
ini_get("allow_url_include")
and set with ini_set("allow_url_include", "1")
If none of the above enabled to diagnose the problem, here are some special situations that could happen :
It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :
require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"
But then you still get the same kind of error.
This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.
For example, the Zend framework file mentioned before could have the following include :
include "Zend/Mail/Protocol/Exception.php"
which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.
In such a case, the only practical solution is to add the directory to your include path.
If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.
To check whether SELinux is enabled on your system, run the sestatus
command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.
To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.
setenforce 0
If you no longer have the problem with SELinux turned off, then this is the root cause.
To solve it, you will have to configure SELinux accordingly.
The following context types will be necessary :
httpd_sys_content_t
for files that you want your server to be able to readhttpd_sys_rw_content_t
for files on which you want read and write accesshttpd_log_t
for log fileshttpd_cache_t
for the cache directoryFor example, to assign the httpd_sys_content_t
context type to your website root directory, run :
semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root
If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs
boolean :
setsebool -P httpd_enable_homedirs 1
In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.
If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache
has been uploaded, or that cache hasn't been cleared.
You can test and fix this by running the following console command:
cache:clear
Apparently, this error can happen also upon calling zip->close()
when some files inside the zip have non-ASCII characters in their filename, such as "é".
A potential solution is to wrap the file name in utf8_decode()
before creating the target file.
Credits to Fran Cano for identifying and suggesting a solution to this issue
I know this question has already been answered, but thought I might add that I found the problem to be folder permissions on my android-sdk
directory.
I tested it out by granting Full Control to Everyone (dodgy, I know...), and the problem went away. I am not sure yet what the specific mix of permissions might be that it was looking for, but I assume some or other service in Eclipse didn't have execute permissions on adb.exe. That said, I'm a complete noob to this - just wanted to put it out there in case someone else had some insights into this.
I am running Windows 7, 64-bit, 4.2.0 Eclipse, and 20.0.0v201206242043 ADT.
I am generally using the way posted by Barry Wark and Rahul Gupta.
Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:
// file.h
extern NSString* const MyConst;
//file.m
NSString* const MyConst = @"Lorem ipsum";
Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.
I have a header file which defines the macro STR_CONST(name, value)
:
// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif
The in my .h/.m pair where I want to define the constant I do the following:
// myfile.h
#import <StringConsts.h>
STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");
// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"
et voila, I have all the information about the constants in .h file only.
The following will check if the documents are equal using standard JDK libraries.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc1 = db.parse(new File("file1.xml")); doc1.normalizeDocument(); Document doc2 = db.parse(new File("file2.xml")); doc2.normalizeDocument(); Assert.assertTrue(doc1.isEqualNode(doc2));
normalize() is there to make sure there are no cycles (there technically wouldn't be any)
The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand xml:space
if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.
Safe fix for Mac (Android studio 4.1+) It is in a different directory now, but symlink helps.
Just run in the Terminal this command
ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1
If you have a different Android Studio version or an installation folder adjust the command accordingly.
You might already know this, but to check that you're getting this stuff right have a look at http://www.subnet-calculator.com/ - you can see there how the bits represent the network and host portions of the address.
IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();
int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
MessageBox.show(i);
--Here i want to get the index or current row from the list
}
++i;
}
Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this
(a-la Java/C++) or explicit @
(a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:
def fubar(x):
self.x = x
class C:
frob = fubar
Now the fubar
function wouldn't work since it would assume that self
is a global variable (and in frob
as well). The alternative would be to execute method's with a replaced global scope (where self
is the object).
The implicit approach would be
def fubar(x)
myX = x
class C:
frob = fubar
This would mean that myX
would be interpreted as a local variable in fubar
(and in frob
as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.
However the current situation works out well:
def fubar(self, x)
self.x = x
class C:
frob = fubar
here when called as a method frob
will receive the object on which it's called via the self
parameter, and fubar
can still be called with an object as parameter and work the same (it is the same as C.frob
I think).
You can use cut with a delimiter like this:
with space delim:
cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv
with tab delim:
cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv
I gave you the version of cut in which you can extract a list of intervals...
Hope it helps!
I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.
#!/bin/bash
# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt
# Let's print some text to fd 3
echo "Roses are red" >&3
echo "Violets are blue" >&3
echo "Poems are cute" >&3
echo "And so are you" >&3
# Close fd 3
exec 3>&-
Then cat
the file on terminal
$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you
This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max
or /proc/sys/fs/file-max
but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)
Anyhow, fd's can be used in a lot of interesting ways.
For in-place sorting in descending order:
int[] numbers = { 1, 2, 3 };
Array.Sort(numbers, (a, b) => b.CompareTo(a));
For out-of-place sorting (no changes to input array):
int[] numbers = { 1, 2, 3 };
var sortedNumbers = numbers.OrderByDescending(x => x).ToArray();
With modern browsers, console.log(functor)
works perfectly (behaves the same was a console.dir
).
If anyone is looking for a VB.Net answer (as I was initially), here it is:
Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))
Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
charity.registeredName.ToLower().Contains(name.ToLower()) Or
charity.alias.ToLower().Contains(name.ToLower()) Or
charity.charityId.ToLower().Contains(name.ToLower())) And
(String.IsNullOrEmpty(referenceNumber) Or
charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function
For a programmer overhead refers to those system resources which are consumed by your code when it's running on a giving platform on a given set of input data. Usually the term is used in the context of comparing different implementations or possible implementations.
For example we might say that a particular approach might incur considerable CPU overhead while another might incur more memory overhead and yet another might weighted to network overhead (and entail an external dependency, for example).
Let's give a specific example: Compute the average (arithmetic mean) of a set of numbers.
The obvious approach is to loop over the inputs, keeping a running total and a count. When the last number is encountered (signaled by "end of file" EOF, or some sentinel value, or some GUI buttom, whatever) then we simply divide the total by the number of inputs and we're done.
This approach incurs almost no overhead in terms of CPU, memory or other resources. (It's a trivial task).
Another possible approach is to "slurp" the input into a list. iterate over the list to calculate the sum, then divide that by the number of valid items from the list.
By comparison this approach might incur arbitrary amounts of memory overhead.
In a particular bad implementation we might perform the sum operation using recursion but without tail-elimination. Now, in addition to the memory overhead for our list we're also introducing stack overhead (which is a different sort of memory and is often a more limited resource than other forms of memory).
Yet another (arguably more absurd) approach would be to post all of the inputs to some SQL table in an RDBMS. Then simply calling the SQL SUM function on that column of that table. This shifts our local memory overhead to some other server, and incurs network overhead and external dependencies on our execution. (Note that the remote server may or may not have any particular memory overhead associated with this task --- it might shove all the values immediately out to storage, for example).
Hypothetically might consider an implementation over some sort of cluster (possibly to make the averaging of trillions of values feasible). In this case any necessary encoding and distribution of the values (mapping them out to the nodes) and the collection/collation of the results (reduction) would count as overhead.
We can also talk about the overhead incurred by factors beyond the programmer's own code. For example compilation of some code for 32 or 64 bit processors might entail greater overhead than one would see for an old 8-bit or 16-bit architecture. This might involve larger memory overhead (alignment issues) or CPU overhead (where the CPU is forced to adjust bit ordering or used non-aligned instructions, etc) or both.
Note that the disk space taken up by your code and it's libraries, etc. is not usually referred to as "overhead" but rather is called "footprint." Also the base memory your program consumes (without regard to any data set that it's processing) is called its "footprint" as well.
Use (V3 version):
(Get-Content c:\temp\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\temp\test.txt
Or for V2:
(Get-Content c:\temp\test.txt) -replace '\[MYID\]', 'MyValue' | Set-Content c:\temp\test.txt
It's 2020 now, for the latest solution, you can use Burp Suite to sniffing https traffic without rooting your Android device.
Steps:
Install Burp Suite
Enable Proxy
Import the certification in your Android phone
Change you Wifi configuration to listening to proxy
Profit!
I wrote the full tutorial and screenshot on how to do it at here: https://www.yodiw.com/monitor-android-network-traffic-with-burp/
You could also disable it and at the moment that you make the submit call enable it. I think is the easiest way :)
To represent the text below in JavaScript:
"'http://example.com'"
Use:
"\"'http://example.com'\""
Or:
'"\'http://example.com\'"'
Note that: We always need to escape the quote that we are surrounding the string with using \
JS Fiddle: http://jsfiddle.net/efcwG/
General Pointers:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
After Php 7.1, The accepted answer won't work for all types of relationships.
Because depending of type the relationship, Eloquent will return a Collection
, a Model
or Null
. And in Php 7.1 count(null)
will throw an error
.
So, to check if the relation exist you can use:
For relationships single: For example hasOne
and belongsTo
if(!is_null($model->relation)) {
....
}
For relationships multiple: For Example: hasMany
and belongsToMany
if ($model->relation->isNotEmpty()) {
....
}
Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/
Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:
PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files
Alternatives for PowerShell v4-:
Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:
& { (Get-ItemProperty `
-LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
-Name $args `
).$args } 'ProgramFilesDir'
By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args
) can then simply be used twice inside the block.
Alternatively, a simple helper function can ease the pain:
function Get-RegValue([String] $KeyPath, [String] $ValueName) {
(Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}
Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0'
- because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName
As for the other answers:
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
<div class="content">
Counter-Strike 1.6 Steam
<img src="images/CSsteam.png">
<a href="#">Koupit</a>
</div>
/*Use this css*/
content {
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
}
content a{
display:inline-block;
padding:10px;
position:absolute;
bottom:10px;
right:10px;
}
This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.
int counter = 1;
System.out.println("Enter a number:");
Scanner OddInput = new Scanner(System.in);
while(OddInput.hasNextInt()){
int Num = OddInput.nextInt();
if (Num %2==0){
System.out.println("Number " + Num + " is Even");
System.out.println("Enter a number:");
}
else {
System.out.println("Number " + Num + " is Odd");
System.out.println("Enter a number:");
}
}
System.out.println("Program Ended");
}
Use a DecimalFormat object with a format string of "0.#".
Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).
This is correct if you plan on using the string later as a query string:
> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'
If you don't want ASCII characters like /
, :
and ?
to be escaped, use encodeURI
instead:
> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
However, for other use-cases, you might need uri-js instead:
> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
Is the opaque overlay for aesthetic purposes?
If so, you can use:
#overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 50;
background: #000;
pointer-events: none;
opacity: 0.8;
color: #fff;
}
'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.
I tried solutions mentioned here but It didn't help me. I mind the solution is layout_width
have to use wrap_content
as value.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1" >
I ran into this after calling UIImagePickerController presentViewController: from the callback to a UIAlertView delegate. I solved the issue by pushing the presentViewController: call off the current execution trace using dispatch_async.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
dispatch_async(dispatch_get_main_queue(), ^{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
if (buttonIndex == 1)
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
else
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController: imagePickerController
animated: YES
completion: nil];
});
}
A self-explanatory simple one-liner to extract token for kubernetes dashboard login.
kubectl describe secret -n kube-system | grep deployment -A 12
Copy the token and paste it on the kubernetes dashboard under token sign in option and you are good to use kubernetes dashboard
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
The existing answers will fail if the string is empty or only has one character. Options:
String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;
or
String substring = str.substring(Math.max(str.length() - 2, 0));
That's assuming that str
is non-null, and that if there are fewer than 2 characters, you just want the original string.
So, After taking a while I figured out that the old push certificate generating service also exists.
You get two options:
Those who want to achieve the old style .p12 certificate can get it from second option. I have not used the first option yet as most of the third-party push notification service providers still need the .p12 format certificate.
git checkout master # first get back to master
git checkout experiment -- app.js # then copy the version of app.js
# from branch "experiment"
See also git how to undo changes of one file?
With the new git switch
and git restore
commands, that would be:
git switch master
git restore --source experiment -- app.js
By default, only the working tree is restored.
If you want to update the index as well (meaning restore the file content, and add it to the index in one command):
git restore --source experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -SW -- app.js
As Jakub Narebski mentions in the comments:
git show experiment:path/to/app.js > path/to/app.js
works too, except that, as detailed in the SO question "How to retrieve a single file from specific revision in Git?", you need to use the full path from the root directory of the repo.
Hence the path/to/app.js used by Jakub in his example.
As Frosty mentions in the comment:
you will only get the most recent state of app.js
But, for git checkout
or git show
, you can actually reference any revision you want, as illustrated in the SO question "git checkout revision of a file in git gui":
$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME
would be the same is $FILENAME is a full path of a versioned file.
$REVISION
can be as shown in git rev-parse
:
experiment@{yesterday}:app.js # app.js as it was yesterday
experiment^:app.js # app.js on the first commit parent
experiment@{2}:app.js # app.js two commits ago
and so on.
schmijos adds in the comments:
you also can do this from a stash:
git checkout stash -- app.js
This is very useful if you're working on two branches and don't want to commit.
Your best option is through PHP: All version requests from the client side cannot be trusted since your Apache could be configured with ServerTokens Prod and ServerSignature Off. See: http://www.petefreitag.com/item/419.cfm
A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:
<div id="left">
content
</div>
<span class="divider"></span>
<div id="right">
content
</div>
With css:
span {
display: inline-block;
width: 0;
height: 1em;
border-left: 1px solid #ccc;
border-right: 1px solid #ccc;
}
Demo at JS Fiddle, adjust the height of the span.container
to adjust the border 'height'.
Or, to use pseudo-elements (::before
or ::after
), given the following HTML:
<div id="left">content</div>
<div id="right">content</div>
The following CSS adds a pseudo-element before any div
element that's the adjacent sibling of another div
element:
div {
display: inline-block;
position: relative;
}
div + div {
padding-left: 0.3em;
}
div + div::before {
content: '';
border-left: 2px solid #000;
position: absolute;
height: 50%;
left: 0;
top: 25%;
}
This worked for me on my Oracle database:
SELECT 'GRANT SELECT, insert, update, delete ON mySchema.' || TABLE_NAME || ' to myUser;'
FROM user_tables
where table_name like 'myTblPrefix%'
Then, copy the results, paste them into your editor, then run them like a script.
You could also write a script and use "Execute Immediate" to run the generated SQL if you don't want the extra copy/paste steps.
You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)
function:
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
In my case I tried with all the options given here, but no one was working properly (angular 1.3.13, ionic 1.0.0, angular-ui-router 0.2.13). The solution was:
.state('tab.friends', {
url: '/friends/:param1/:param2',
views: {
'tab-friends': {
templateUrl: 'templates/tab-friends.html',
controller: 'FriendsCtrl'
}
}
})
and in the state.go:
$state.go('tab.friends', {param1 : val1, param2 : val2});
Cheers
You need add parameter errors='coerce'
to function to_numeric
:
ID = pd.to_numeric(ID, errors='coerce')
If ID
is column:
df.ID = pd.to_numeric(df.ID, errors='coerce')
but non numeric are converted to NaN
, so all values are float
.
For int
need convert NaN
to some value e.g. 0
and then cast to int
:
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
Sample:
df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
ID
0 4806105017087
1 4806105017087
2 CN414149
print (pd.to_numeric(df.ID, errors='coerce'))
0 4.806105e+12
1 4.806105e+12
2 NaN
Name: ID, dtype: float64
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
ID
0 4806105017087
1 4806105017087
2 0
EDIT: If use pandas 0.25+ then is possible use integer_na
:
df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
ID
0 4806105017087
1 4806105017087
2 NaN
If you're using Ionic, you can solve it directly from config.xml by adding inside platform ios tag:
<platform name="ios">
.
.
.
<config-file target="*-Info.plist" parent="NSPhotoLibraryUsageDescription">
<string>photo library usage description</string>
</config-file>
<config-file target="*-Info.plist" parent="NSCameraUsageDescription">
<string>camera usage description</string>
</config-file>
.
.
.
</platform>
I'd like to thank @BHUPI answer too.
you can use unfactor()
function from "varhandle" package form CRAN:
library("varhandle")
my_iris <- data.frame(Sepal.Length = factor(iris$Sepal.Length),
sample_id = factor(1:nrow(iris)))
my_iris <- unfactor(my_iris)
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
Suppose you have created a new branch on GitHub with the name feature-branch.
FETCH
git pull --all Pull all remote branches
git branch -a List all branches now
Checkout and switch to the feature-branch directory. You can simply copy the branch name from the output of branch -a command above
git checkout -b feature-branch
VALIDATE
Next use the git branch command to see the current branch. It will show feature-branch with * In front of it
git branch
COMMIT
git add . add all files
git commit -m "Rafactore code or use your message"
Take update and the push changes on the origin server
git pull origin feature-branch
git push origin feature-branch
@media all {
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
} }
A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)
I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).
So in the parent document, add an event listener:
window.addEventListener('message', function(e) {
var $iframe = jQuery("#myIframe");
var eventName = e.data[0];
var data = e.data[1];
switch(eventName) {
case 'setHeight':
$iframe.height(data);
break;
}
}, false);
And inside the iframe, write a function to post the message:
function resize() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");
}
Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:
<body onLoad="resize();">
Just to add some performance insights.
A few years ago I had a project, where we had issues trying to set a large HTML / Text to various HTML elements.
It appeared, that "recreating" the element and injecting it to the DOM was way faster than any of the suggested methods to update the DOM content.
So something like:
var text = "very big content";_x000D_
$("#regTitle").remove();_x000D_
$("<div id='regTitle'>" + text + "</div>").appendTo("body");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Should get you a better performance. I haven't recently tried to measure that (browsers should be clever these days), but if you're looking for performance it may help.
The downside is that you will have more work to keep the DOM and the references in your scripts pointing to the right object.
In my case this Microsoft.Owin.Host.SystemWeb package is present in the project.
But below two tags are not present in web.config.
<add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:appStartup" value="namespace.className.methodName" />
after adding them it works smoothly.
The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".
This could be due to a few things:
If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.
If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.
If there are too many open connections to the database service, it could refuse new connections.
Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.
One of my favorite uses of reflection is the below Java dump method. It takes any object as a parameter and uses the Java reflection API to print out every field name and value.
import java.lang.reflect.Array;
import java.lang.reflect.Field;
public static String dump(Object o, int callCount) {
callCount++;
StringBuffer tabs = new StringBuffer();
for (int k = 0; k < callCount; k++) {
tabs.append("\t");
}
StringBuffer buffer = new StringBuffer();
Class oClass = o.getClass();
if (oClass.isArray()) {
buffer.append("\n");
buffer.append(tabs.toString());
buffer.append("[");
for (int i = 0; i < Array.getLength(o); i++) {
if (i < 0)
buffer.append(",");
Object value = Array.get(o, i);
if (value.getClass().isPrimitive() ||
value.getClass() == java.lang.Long.class ||
value.getClass() == java.lang.String.class ||
value.getClass() == java.lang.Integer.class ||
value.getClass() == java.lang.Boolean.class
) {
buffer.append(value);
} else {
buffer.append(dump(value, callCount));
}
}
buffer.append(tabs.toString());
buffer.append("]\n");
} else {
buffer.append("\n");
buffer.append(tabs.toString());
buffer.append("{\n");
while (oClass != null) {
Field[] fields = oClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
buffer.append(tabs.toString());
fields[i].setAccessible(true);
buffer.append(fields[i].getName());
buffer.append("=");
try {
Object value = fields[i].get(o);
if (value != null) {
if (value.getClass().isPrimitive() ||
value.getClass() == java.lang.Long.class ||
value.getClass() == java.lang.String.class ||
value.getClass() == java.lang.Integer.class ||
value.getClass() == java.lang.Boolean.class
) {
buffer.append(value);
} else {
buffer.append(dump(value, callCount));
}
}
} catch (IllegalAccessException e) {
buffer.append(e.getMessage());
}
buffer.append("\n");
}
oClass = oClass.getSuperclass();
}
buffer.append(tabs.toString());
buffer.append("}\n");
}
return buffer.toString();
}
you can use the <pre>
tag to prevent multiple spaces and linebreaks from being collapsed into one. Or you could use
for a typical space (non-breaking space) and <br />
(or <br>
) for line breaks.
But don't do <br><br><br><br>
just use a <p>
tag and adjust the margins with CSS.
<p style="margin-top: 20px;">Some copy...</p>
Although, you should define the styles globally, and not inline as I have done in this example.
When you are outputting strings from PHP you can use "\n" for a new line, and "\t" for a tab.
<?php echo "This is one line\nThis is another line"; ?>
Although, flags like \n or \t only work in double quotes (") not single wuotes (').
Anyone looking for Swift 3
1) Make sure your UITextField's Delegate is wired to your ViewController in the Storyboard
2) Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )
3) Use the delegate method below
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false }
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
Spy can be useful when you want to create unit tests for legacy code.
I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.
If you have something like this code:
public void transfer( DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService,
double amount, String fromAccount, String toAccount){
withdrawMoneyService.withdraw(fromAccount,amount);
depositMoneyService.deposit(toAccount,amount);
}
You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.
But with some, legacy code, dependency is in the code like this:
public void transfer(String fromAccount, String toAccount, double amount){
this.depositeMoneyService = new DepositMoneyService();
this.withdrawMoneyService = new WithdrawMoneyService();
withdrawMoneyService.withdraw(fromAccount,amount);
depositeMoneyService.deposit(toAccount,amount);
}
Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.
Alternative is that you can extract the dependency out like this:
public void transfer(String fromAccount, String toAccount, double amount){
this.depositeMoneyService = proxyDepositMoneyServiceCreator();
this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();
withdrawMoneyService.withdraw(fromAccount,amount);
depositeMoneyService.deposit(toAccount,amount);
}
DepositMoneyService proxyDepositMoneyServiceCreator() {
return new DepositMoneyService();
}
WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
return new WithdrawMoneyService();
}
Then you can use the spy the inject the dependency like this:
DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);
TransferMoneyService target = spy(new TransferMoneyService());
doReturn(mockDepositMoneyService)
.when(target).proxyDepositMoneyServiceCreator();
doReturn(mockWithdrawMoneyService)
.when(target).proxyWithdrawMoneyServiceCreator();
More detail in the link above.