another way would be to use dplyr
package:
x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))
int puts(const char *s);
puts() writes the string s and a trailing newline to stdout.
int printf(const char *format, ...);
The function printf() writes output to stdout, under the control of a format string that specifies how subsequent arguments are converted for output.
I'll use this opportunity to ask you to read the documentation.
Are you sure you're not confusing Oracle database with Oracle SQL Developer?
The database itself has no date format, the date comes out of the database in raw form. It's up to the client software to render it, and SQL Developer does use YYYY-MM-DD as its default format, which is next to useless, I agree.
edit: As was commented below, SQL Developer can be reconfigured to display DATE values properly, it just has bad defaults.
As of 2017, it seems there's no reliable way to detect an app is installed, and the redirection trick won't work everywhere.
For those like me who needs to deep link directly from emails (quite common), it is worth noting the following:
Sending emails with appScheme:// won't work fine because the links will be filtered in Gmail
Redirecting automatically to appScheme:// is blocked by Chrome: I suspect Chrome requires the redirection to be synchronous to an user interaction (like a click)
You can now deep link without appScheme:// and it's better but it requires a modern platform and additional setup. Android iOS
It is worth noting that other people already thought about this in depth. If you look at how Slack implements his "magic link" feature, you can notice that:
I am trying to make an update for Spring STS 3.6.3 to the version 3.6.4 in Eclipse Luna (4.4.1) and I tried the following solution and it worked for me:
This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype
It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.
This error message...
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Your main issue is the Chrome browser is not installed at the default location within your system.
The server i.e. ChromeDriver expects you to have Chrome installed in the default location for each system as per the image below:
1For Linux systems, the ChromeDriver expects /usr/bin/google-chrome
to be a symlink to the actual Chrome binary.
In case you are using a Chrome executable in a non-standard location you have to override the Chrome binary location as follows:
Python Solution:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = "C:\\path\\to\\chrome.exe" #chrome binary location specified here
options.add_argument("--start-maximized") #open Browser in maximized mode
options.add_argument("--no-sandbox") #bypass OS security model
options.add_argument("--disable-dev-shm-usage") #overcome limited resource problems
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get('http://google.com/')
Java Solution:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions opt = new ChromeOptions();
opt.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"); //chrome binary location specified here
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(opt);
driver.get("https://www.google.com/");
Here is a solution to prevent session shearing between browser tabs for a java application. This will work for IE (JSP/Servlet)
1)first page JS
BODY onload="javascript:initPageLoad()"
function initPageLoad() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText;
top.document.title=serverResponse;
}
};
xmlhttp.open("GET", 'data.do', true);
xmlhttp.send();
}
2)common JS for all pages
window.onunload = function() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var serverResponse = xmlhttp.responseText;
}
};
xmlhttp.open("GET", 'data.do?reset=true', true);
xmlhttp.send();
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
init();
clearInterval(readyStateCheckInterval);
}}, 10);
function init(){
if(document.title==""){
window.onunload=function() {};
window.open('', '_self', ''); window.close();
}
}
3)web.xml - servlet mapping
<servlet-mapping>
<servlet-name>myAction</servlet-name>
<url-pattern>/data.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>myAction</servlet-name>
<servlet-class>xx.xxx.MyAction</servlet-class>
</servlet>
4)servlet code
public class MyAction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Integer sessionCount = (Integer) request.getSession().getAttribute(
"sessionCount");
PrintWriter out = response.getWriter();
Boolean reset = Boolean.valueOf(request.getParameter("reset"));
if (reset)
sessionCount = new Integer(0);
else {
if (sessionCount == null || sessionCount == 0) {
out.println("hello Title");
sessionCount = new Integer(0);
}
sessionCount++;
}
request.getSession().setAttribute("sessionCount", sessionCount);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "private, no-store, no-cache, must- revalidate");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
}
I think the issue is here:
<template id="newtemp" :name ="{{user.name}}">
When you prefix the prop with :
you are indicating to Vue that it is a variable, not a string. So you don't need the {{}}
around user.name
. Try:
<template id="newtemp" :name ="user.name">
EDIT-----
The above is true, but the bigger issue here is that when you change the URL and go to a new route, the original component disappears. In order to have the second component edit the parent data, the second component would need to be a child component of the first one, or just a part of the same component.
It's simple. Just add:
PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;
First of all go to apache/bin/conf/httpd.conf and make sure that mod_deflate.so is enabled.
Then go to the .htaccess file and add this line:
SetOutputFilter DEFLATE
This should output all the content served as gzipped, i have tried it and it works.
I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6. So you only need to write toString()
method in your enum.
public class CustomObjectMapper extends ObjectMapper {
@PostConstruct
public void customConfiguration() {
// Uses Enum.toString() for serialization of an Enum
this.enable(WRITE_ENUMS_USING_TO_STRING);
// Uses Enum.toString() for deserialization of an Enum
this.enable(READ_ENUMS_USING_TO_STRING);
}
}
There are more enum-related features available, see here:
https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features
always use with statement like ;WITH
then you'll never get this error. The WITH command required a ;
between it and any previous command, by always using ;WITH
you'll never have to remember to do this.
see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:
When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.
You can use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
But I don't know whether it should be considered more right than to use Calendar ...
For those people using Python, you may consider using Selenium Wire, which can set request headers, as well as provide you with the ability to inspect requests and responses.
from seleniumwire import webdriver # Import from seleniumwire
# Create a new instance of the Firefox driver (or Chrome)
driver = webdriver.Firefox()
# Create a request interceptor
def interceptor(request):
del request.headers['Referer'] # Delete the header first
request.headers['Referer'] = 'some_referer'
# Set the interceptor on the driver
driver.request_interceptor = interceptor
# All requests will now use 'some_referer' for the referer
driver.get('https://mysite')
By using ''
you are making it to string. Use without inverted commas it will work fine.
This should work:
System.currentTimeMillis();
I ran into this issue yesterday. I submitted multiple builds with a variety of different settings. What finally worked for me was submitting through Application Loader with no bitcode.
I hope this helps someone avoid the headache I went through. Its been 24 hours and the apps submitted through Xcode are all still "processing", the one submitted through Application Loader was available within an hour or so.
I have tried all of the above solutions (which all bring valid points), but nothing was working for me.
Until I found that my MySQL table field mappings in C# was using an incorrect type: MySqlDbType.Blob . I changed it to MySqlDbType.Text and now I can write all the UTF8 symbols I want!
p.s. My MySQL table field is of the "LongText" type. However, when I autogenerated the field mappings using MyGeneration software, it automatically set the field type as MySqlDbType.Blob in C#.
Interestingly, I have been using the MySqlDbType.Blob type with UTF8 characters for many months with no trouble, until one day I tried writing a string with some specific characters in it.
Hope this helps someone who is struggling to find a reason for the error.
I added customBinding to the web.config.
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomSoapBinding">
<security includeTimestamp="false"
authenticationMode="UserNameOverTransport"
defaultAlgorithmSuite="Basic256"
requireDerivedKeys="false"
messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
</security>
<textMessageEncoding messageVersion="Soap11"></textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2000000000"/>
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://test.com:443/services/testService"
binding="customBinding"
bindingConfiguration="CustomSoapBinding"
contract="testService.test"
name="test" />
</client>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
After adding customBinding, I can pass username and password to client service like as follows:
service.ClientCridentials.UserName.UserName = "testUser";
service.ClientCridentials.UserName.Password = "testPass";
In this way you can pass username, password in the header to a SOAP WCF Service.
If you are restrained from having the files in your directory, you can run this code in a script file from the Host machine.
#!/bin/sh
OPTIONS=`vagrant ssh-config | awk -v ORS=' ' '{print "-o " $1 "=" $2}'`
scp ${OPTIONS} /File/To/Copy vagrant@YourServer:/Where/To/Put/File
In this setup, you only need to change /File/To/Copy
to the file or files you want to copy and then /Where/To/Put/File
is the location on the VM you wish to have the files copied to.
If you create this file and call it copyToServer.sh
you can then run the sh
command to push those files.
sh ./copyToServer.sh
As a final note, you cannot run this code as a provisioner
because that runs on the Guest server, while this code runs from the Host.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use &
and |
it will always evaluate both sides of the expression.
If you want to swap string. it's already the efficient way to do that.
However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:
int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;
In the Powershell, cd to the .exe file location. For example:
cd C:\Users\Administrators\Downloads
PS C:\Users\Administrators\Downloads> & '.\aaa.exe'
The installer pops up and follow the instruction on the screen.
In my case (running the server locally on windows) I needed to clean the cache after changing the httpd.conf file.
\modules\apache\bin> ./htcacheclean.exe -t
I'd like to add an answer here that is really just a conglomerate of other answers, but I think it may be more complete.
You know you have a Git submodule when you have these two things.
Your .gitmodules
has an entry like so:
[submodule "SubmoduleTestRepo"]
path = SubmoduleTestRepo
url = https://github.com/jzaccone/SubmoduleTestRepo.git
You have a submodule object (named SubmoduleTestRepo in this example) in your Git repository. GitHub shows these as "submodule" objects. Or do git submodule status
from a command line. Git submodule objects are special kinds of Git objects, and they hold the SHA information for a specific commit.
Whenever you do a git submodule update
, it will populate your submodule with content from the commit. It knows where to find the commit because of the information in the .gitmodules
.
Now, all the -b
does is add one line in your .gitmodules
file. So following the same example, it would look like this:
[submodule "SubmoduleTestRepo"]
path = SubmoduleTestRepo
url = https://github.com/jzaccone/SubmoduleTestRepo.git
branch = master
Note: only branch name is supported in a
.gitmodules
file, but SHA and TAG are not supported! (instead of that, the branch's commit of each module can be tracked and updated using "git add .
", for example likegit add ./SubmoduleTestRepo
, and you do not need to change the.gitmodules
file each time)
The submodule object is still pointing at a specific commit. The only thing that the -b
option buys you is the ability to add a --remote
flag to your update as per Vogella's answer:
git submodule update --remote
Instead of populating the content of the submodule to the commit pointed to by the submodule, it replaces that commit with the latest commit on the master branch, THEN it populates the submodule with that commit. This can be done in two steps by djacobs7 answer. Since you have now updated the commit the submodule object is pointing to, you have to commit the changed submodule object into your Git repository.
git submodule add -b
is not some magically way to keep everything up to date with a branch. It is simply adds information about a branch in the .gitmodules
file and gives you the option to update the submodule object to the latest commit of a specified branch before populating it.
Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so
let markdown = `
1. Apple
2. Mango
this is juicy
3. Orange
`
Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:
x <- 1:10
y <- x + c(-0.5,0.5)
plot(x,y, xlim=c(0,11), ylim=c(-1,12))
fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )
fit7 <- lm( y ~ x + cos(x*pi) )
xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')
Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).
sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time
example: sc.next().charat(2)------------>>>>>>>>
Slightly shorter code using insertRow
and insertCell
:
function tableCreate(){_x000D_
var body = document.body,_x000D_
tbl = document.createElement('table');_x000D_
tbl.style.width = '100px';_x000D_
tbl.style.border = '1px solid black';_x000D_
_x000D_
for(var i = 0; i < 3; i++){_x000D_
var tr = tbl.insertRow();_x000D_
for(var j = 0; j < 2; j++){_x000D_
if(i == 2 && j == 1){_x000D_
break;_x000D_
} else {_x000D_
var td = tr.insertCell();_x000D_
td.appendChild(document.createTextNode('Cell'));_x000D_
td.style.border = '1px solid black';_x000D_
if(i == 1 && j == 1){_x000D_
td.setAttribute('rowSpan', '2');_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
body.appendChild(tbl);_x000D_
}_x000D_
tableCreate();
_x000D_
Also, this doesn't use some "bad practices", such as setting a border
attribute instead of using CSS, and it accesses the body
through document.body
instead of document.getElementsByTagName('body')[0]
;
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
Yes using Option Explicit
is a good habit. Using .Select
however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet
which might not be what you actually wanted.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
Else
Exit For
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
NOTE
If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10
If you want to copy all rows which have data then use this code.
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
Hope this is what you wanted?
Sid
I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h
header you are looking for.
The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.
The following MySQL statement should modify your column to accept NULLs.
ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().
code::
StringBuilder sb = new StringBuilder();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om){
om.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
String result = sb.toString();
Check this: System.currentTimeMillis.
With this you can calculate the time of your method by doing:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
Always open in binary mode, in this case
file = open("Fruits.obj",'rb')
In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape
to get the shape of the tensor.
tensor_shape = tensor.shape
print(tensor_shape)
Also I found solving for my way.
Before launch app i granted root to file-explorer and did not disable permission on write/read when exit from app.
My app can not use external memory while i did restrat device for resetting all permissions.
i think this can be as simple
let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context
and payload
which is your data you want to pass in action so let take an example
Setting up Action
instead of
actions: {
authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
}
do
actions: {
authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
}
Calling (dispatching) Action
instead of
this.$store.dispatch({
type: 'authenticate',
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
do
this.$store.dispatch('authenticate',{
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
hope this gonna help
Although it is quite an old question, another approach is to change AppendDataBoundItems property. So the code will be:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>
You can use .html()
to get content of span
and or div
elements.
example:
var monthname = $(this).html();
alert(monthname);
Here is a simple HTML and JavaScript solution I prefer:
//js function to allow only checking of one weekday checkbox at a time:
function checkOnlyOne(b){
var x = document.getElementsByClassName('daychecks');
var i;
for (i = 0; i < x.length; i++) {
if(x[i].value != b) x[i].checked = false;
}
}
Day of the week:
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Monday" />Mon
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Tuesday" />Tue
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Wednesday" />Wed
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Thursday" />Thu
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Friday" />Fri
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Saturday" />Sat
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Sunday" />Sun <br /><br />
Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -
select distinct on (pd)
regexp_replace(rndc.pd, '\\s+', '_','g') as pd
from rndc14_ndc_mstr rndc;
I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).
Read my answer there for a fuller explaination, but in short:
They removed it deliberately, because compat mode is not actually really very good for testing compatibility.
If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.
The only way to get compat mode in IE11 is to set the X-UA-Compatible
header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.
If you'd like to gather more information on the error and if the error occurs in the first few iterations, I suggest you run the experiment in CPU-only mode (no GPUs). The error message will be much more specific.
Source: https://github.com/tensorflow/tensor2tensor/issues/574
public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
JSONObject json = new JSONObject();
// get the keys of json object
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(obj.getJSONObject(key), keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(jArray.getJSONObject(i), keyString, newValue);
}
}
}
return obj;
}
you can also use this code in your style.xml file so you don't need to write anything else in your activity.java
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>
<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address
alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
FYI, sender
and e
are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
This is how I do it with Factory / Services and simple dependency injection (DI).
myApp = angular.module('myApp', [])
# PeopleService holds the "data".
angular.module('myApp').factory 'PeopleService', ()->
[
{name: "Jack"}
]
# Controller where PeopleService is injected
angular.module('myApp').controller 'PersonFormCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
$scope.people = PeopleService
$scope.person = {}
$scope.add = (person)->
# Simply push some data to service
PeopleService.push angular.copy(person)
]
# ... and again consume it in another controller somewhere...
angular.module('myApp').controller 'PeopleListCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
$scope.people = PeopleService
]
If someone referring how to do the same feature (reading OTP using received SMS) on Xamarin Android like me :
Add this code to your AndroidManifest.xml file :
<receiver android:name=".listener.BroadcastReveiverOTP">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.BROADCAST_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
Then create your BroadcastReveiver class in your Android Project.
[BroadcastReceiver(Enabled = true)] [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = (int)IntentFilterPriority.HighPriority)]
public class BroadcastReveiverOTP : BroadcastReceiver {
public static readonly string INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
protected string message, address = string.Empty;
public override void OnReceive(Context context, Intent intent)
{
if (intent.HasExtra("pdus"))
{
var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
foreach (var item in smsArray)
{
var sms = SmsMessage.CreateFromPdu((byte[])item);
address = sms.OriginatingAddress;
if (address.Equals("NotifyDEMO"))
{
message = sms.MessageBody;
string[] pin = message.Split(' ');
if (!string.IsNullOrWhiteSpace(pin[0]))
{
// NOTE : Here I'm passing received OTP to Portable Project using MessagingCenter. So I can display the OTP in the relevant entry field.
MessagingCenter.Send<object, string>(this,MessengerKeys.OnBroadcastReceived, pin[0]);
}
}
}
}
}
}
Register this BroadcastReceiver class in your MainActivity class on Android Project:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
// Initialize your class
private BroadcastReveiverOTP _receiver = new BroadcastReveiverOTP ();
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
// Register your receiver : RegisterReceiver(_receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
}
oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.
There is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
This is because of
String outStr = obj.toString("UTF-8");
Send the byte[]
which you can get from your ByteArrayOutputStream
and use it as such in your ByteArrayInputStream
to construct your GZIPInputStream
. Following are the changes which need to be done in your code.
byte[] compressed = compress(string); //In the main method
public static byte[] compress(String str) throws Exception {
...
...
return obj.toByteArray();
}
public static String decompress(byte[] bytes) throws Exception {
...
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
...
}
No you cannot. user_name is doesn't exist until return time.
use Json & jQuery. It's way easier than oldschool javascript
function savedata1() {
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
td_1: $row.find(':nth-child(1)').text(),
td_2: $row.find(':nth-child(2)').text(),
td_3: $row.find(':nth-child(3)').text()
};
}).get();
It doesn't matter if the executable has arguments or not. To run GDB on any binary with a generated core file, the syntax is below.
Syntax:
gdb <binary name> <generated core file>
Eg:
gdb l3_entity 6290-corefile
Let me take the below example for more understanding.
bash-4.1$ **gdb l3_entity 6290-corefile**
**Core was generated** by `/dir1/dir2/dir3/l3_entity **Program terminated with signal SIGABRT, Aborted.**
#0
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
(gdb)
From the above output, you can guess something about core, whether it is a NULL access, SIGABORT, etc..
These numbers #0 to #10 are the stack frames of GDB. These stack frames are not of your binary. In the above 0 - 10 frames if you suspect anything wrong select that frame
(gdb) frame 8
Now to see more details about it:
(gdb) list +
To investigate the issue further, you can print the suspected variable values here at this point in time.
(gdb) print thread_name
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
Inspired from this post and that post, I use this code to generate and verify hashed salted passwords. It only uses JDK provided classes, no external dependency.
The process is:
getNextSalt
hash
method to generate a salted and hashed password. The method returns a byte[]
which you can save as is in a database with the saltisExpectedPassword
method to check that the details match/**
* A utility class to hash passwords and check passwords vs hashed values. It uses a combination of hashing and unique
* salt. The algorithm used is PBKDF2WithHmacSHA1 which, although not the best for hashing password (vs. bcrypt) is
* still considered robust and <a href="https://security.stackexchange.com/a/6415/12614"> recommended by NIST </a>.
* The hashed value has 256 bits.
*/
public class Passwords {
private static final Random RANDOM = new SecureRandom();
private static final int ITERATIONS = 10000;
private static final int KEY_LENGTH = 256;
/**
* static utility class
*/
private Passwords() { }
/**
* Returns a random salt to be used to hash a password.
*
* @return a 16 bytes random salt
*/
public static byte[] getNextSalt() {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
return salt;
}
/**
* Returns a salted and hashed password using the provided hash.<br>
* Note - side effect: the password is destroyed (the char[] is filled with zeros)
*
* @param password the password to be hashed
* @param salt a 16 bytes salt, ideally obtained with the getNextSalt method
*
* @return the hashed password with a pinch of salt
*/
public static byte[] hash(char[] password, byte[] salt) {
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
Arrays.fill(password, Character.MIN_VALUE);
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return skf.generateSecret(spec).getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);
} finally {
spec.clearPassword();
}
}
/**
* Returns true if the given password and salt match the hashed value, false otherwise.<br>
* Note - side effect: the password is destroyed (the char[] is filled with zeros)
*
* @param password the password to check
* @param salt the salt used to hash the password
* @param expectedHash the expected hashed value of the password
*
* @return true if the given password and salt match the hashed value, false otherwise
*/
public static boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) {
byte[] pwdHash = hash(password, salt);
Arrays.fill(password, Character.MIN_VALUE);
if (pwdHash.length != expectedHash.length) return false;
for (int i = 0; i < pwdHash.length; i++) {
if (pwdHash[i] != expectedHash[i]) return false;
}
return true;
}
/**
* Generates a random password of a given length, using letters and digits.
*
* @param length the length of the password
*
* @return a random password
*/
public static String generateRandomPassword(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int c = RANDOM.nextInt(62);
if (c <= 9) {
sb.append(String.valueOf(c));
} else if (c < 36) {
sb.append((char) ('a' + c - 10));
} else {
sb.append((char) ('A' + c - 36));
}
}
return sb.toString();
}
}
I tried above answers and they didn't help in my case.
I solved it with this link help: http://vjscrazzy.blogspot.co.il/2016/02/failed-to-sync-gradle-project.html
step 1) file>Setttings>appearance and behaviour> system setttings>HTTP proxy> set No Proxy
step 2) build,execution and deployment> Build tools > gradle> now under project level settings > select local gradle distribution> gradle home = F:/Program Files/Android/Android Studio/gradle/gradle-2.4
After that, I did these changes(because it still wrote me some other errors)
Android Studio asked me:
Android Studio asked me to update my Gradle version (which he didn't before)
Enable - Tools> Android> Enable ADB integration.
Also, if your working in a team with repositories, it's important to check that the version of the Andorid Studio is the same.
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
Just type "cmd" to location bar, that's it. It will start a new command prompt in current path.
This solution was confirmed to work in Windows XP, Vista, 7, 8 and 10 (including Creators Update).
Keystrokes to move the focus to the location bar:
This worked for me with log4j2 and xml parameters:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
<Properties>
<Property name="log-path">/some_path/logs/</Property>
<Property name="app-id">my_app</Property>
</Properties>
<Appenders>
<RollingFile name="file-log" fileName="${log-path}/${app-id}.log"
filePattern="${log-path}/${app-id}-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="org.springframework.jdbc.core" level="trace" additivity="false">
<appender-ref ref="file-log" />
<appender-ref ref="console" />
</Logger>
<Root level="info" additivity="false">
<appender-ref ref="file-log" />
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>
Result console and file log was:
JdbcTemplate - Executing prepared SQL query
JdbcTemplate - Executing prepared SQL statement [select a, b from c where id = ? ]
StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [my_id], value class [java.lang.String], SQL type unknown
Just copy/past
HTH
Some editions of find, mostly on linux systems, possibly on others aswell support -regex and -regextype options, which finds files with names matching the regex.
for example
find . -regextype posix-egrep -regex ".*\.(py|html)$"
should do the trick in the above example. However this is not a standard POSIX find function and is implementation dependent.
Posting this as an equally viable alternative to @Binil Thomas's answer - tried to add it as a comment, but was not convinced of the readability of it all.
int index = 0;
for (Object key : map.keySet()) {
Object value = map.get(key);
++index;
}
Probably doesn't help the original question poster since this is the literal situation they were trying to avoid, but may aid others searching for an easy answer.
The shortcut is:
Windows/English Ctrl+Shift+\
Windows/German Ctrl+Shift+^
I am using below solution for IIS hosting in ASP.NET compatibility mode. Credits to Rodney Viana's MSDN blog.
Add following to your web.config under appSettings:
<add key="LogPath" value="C:\\logpath" />
<add key="LogRequestResponse" value="true" />
Replace your global.asax.cs with below (also fix namespace name):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text;
using System.IO;
using System.Configuration;
namespace Yournamespace
{
public class Global : System.Web.HttpApplication
{
protected static bool LogFlag;
protected static string fileNameBase;
protected static string ext = "log";
// One file name per day
protected string FileName
{
get
{
return String.Format("{0}{1}.{2}", fileNameBase, DateTime.Now.ToString("yyyy-MM-dd"), ext);
}
}
protected void Application_Start(object sender, EventArgs e)
{
LogFlag = bool.Parse(ConfigurationManager.AppSettings["LogRequestResponse"].ToString());
fileNameBase = ConfigurationManager.AppSettings["LogPath"].ToString() + @"\C5API-";
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (LogFlag)
{
// Creates a unique id to match Rquests with Responses
string id = String.Format("Id: {0} Uri: {1}", Guid.NewGuid(), Request.Url);
FilterSaveLog input = new FilterSaveLog(HttpContext.Current, Request.Filter, FileName, id);
Request.Filter = input;
input.SetFilter(false);
FilterSaveLog output = new FilterSaveLog(HttpContext.Current, Response.Filter, FileName, id);
output.SetFilter(true);
Response.Filter = output;
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
class FilterSaveLog : Stream
{
protected static string fileNameGlobal = null;
protected string fileName = null;
protected static object writeLock = null;
protected Stream sinkStream;
protected bool inDisk;
protected bool isClosed;
protected string id;
protected bool isResponse;
protected HttpContext context;
public FilterSaveLog(HttpContext Context, Stream Sink, string FileName, string Id)
{
// One lock per file name
if (String.IsNullOrWhiteSpace(fileNameGlobal) || fileNameGlobal.ToUpper() != fileNameGlobal.ToUpper())
{
fileNameGlobal = FileName;
writeLock = new object();
}
context = Context;
fileName = FileName;
id = Id;
sinkStream = Sink;
inDisk = false;
isClosed = false;
}
public void SetFilter(bool IsResponse)
{
isResponse = IsResponse;
id = (isResponse ? "Reponse " : "Request ") + id;
//
// For Request only read the incoming stream and log it as it will not be "filtered" for a WCF request
//
if (!IsResponse)
{
AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
AppendToFile(id);
if (context.Request.InputStream.Length > 0)
{
context.Request.InputStream.Position = 0;
byte[] rawBytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(rawBytes, 0, rawBytes.Length);
context.Request.InputStream.Position = 0;
AppendToFile(rawBytes);
}
else
{
AppendToFile("(no body)");
}
}
}
public void AppendToFile(string Text)
{
byte[] strArray = Encoding.UTF8.GetBytes(Text);
AppendToFile(strArray);
}
public void AppendToFile(byte[] RawBytes)
{
bool myLock = System.Threading.Monitor.TryEnter(writeLock, 100);
if (myLock)
{
try
{
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
stream.Position = stream.Length;
stream.Write(RawBytes, 0, RawBytes.Length);
stream.WriteByte(13);
stream.WriteByte(10);
}
}
catch (Exception ex)
{
string str = string.Format("Unable to create log. Type: {0} Message: {1}\nStack:{2}", ex, ex.Message, ex.StackTrace);
System.Diagnostics.Debug.WriteLine(str);
System.Diagnostics.Debug.Flush();
}
finally
{
System.Threading.Monitor.Exit(writeLock);
}
}
}
public override bool CanRead
{
get { return sinkStream.CanRead; }
}
public override bool CanSeek
{
get { return sinkStream.CanSeek; }
}
public override bool CanWrite
{
get { return sinkStream.CanWrite; }
}
public override long Length
{
get
{
return sinkStream.Length;
}
}
public override long Position
{
get { return sinkStream.Position; }
set { sinkStream.Position = value; }
}
//
// For WCF this code will never be reached
//
public override int Read(byte[] buffer, int offset, int count)
{
int c = sinkStream.Read(buffer, offset, count);
return c;
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return sinkStream.Seek(offset, direction);
}
public override void SetLength(long length)
{
sinkStream.SetLength(length);
}
public override void Close()
{
sinkStream.Close();
isClosed = true;
}
public override void Flush()
{
sinkStream.Flush();
}
// For streamed responses (i.e. not buffered) there will be more than one Response (but the id will match the Request)
public override void Write(byte[] buffer, int offset, int count)
{
sinkStream.Write(buffer, offset, count);
AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
AppendToFile(id);
AppendToFile(buffer);
}
}
}
It should create log file in the folder LogPath with request and response XML.
You can use the Windows API function ShellExecute
to do so:
Option Explicit
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal Operation As String, _
ByVal Filename As String, _
Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Public Sub OpenUrl()
Dim lSuccess As Long
lSuccess = ShellExecute(0, "Open", "www.google.com")
End Sub
Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute
would execute any command with the user's permissions, also a format c:
would be executed if the user is an administrator.
I would use .Equals()
for comparison instead of ==
.
Like so:
MyClass item = MyList.Find(item => item.name.Equals("foo"));
Particularly because it gives you options like StringComparison, which is awesome. Example:
MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);
This enables your code to ignore special characters, upper and lower case. There are more options.
An optional parameter is just tagged with an attribute. This attribute tells the compiler to insert the default value for that parameter at the call-site.
The call obj2.TestMethod();
is replaced by obj2.TestMethod(false);
when the C# code gets compiled to IL, and not at JIT-time.
So in a way it's always the caller providing the default value with optional parameters. This also has consequences on binary versioning: If you change the default value but don't recompile the calling code it will continue to use the old default value.
On the other hand, this disconnect means you can't always use the concrete class and the interface interchangeably.
You already can't do that if the interface method was implemented explicitly.
Depending on the nature of the duplicate rows, it looks like all you want is to have case-sensitivity on those columns. Setting the collation on these columns should be what you're after:
SELECT DISTINCT p.IDNO COLLATE SQL_Latin1_General_CP1_CI_AS, p.FirstName COLLATE SQL_Latin1_General_CP1_CI_AS, p.LastName COLLATE SQL_Latin1_General_CP1_CI_AS
FROM people P
Maybe .value_counts()
?
>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0 1
1 2
2 2
3 3
4 3
5 3
6 fred
7 1.8
8 1.8
>>> counts = my_series.value_counts()
>>> counts
3 3
2 2
1.8 2
fred 1
1 1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}
Click the vertical ellipsis button ( ? ) then choose the desired docking option.
Long-hold the dock icon in the top right. It pops up an option to change the docking
To change the split between the HTML and CSS panels, go in DevTools to Settings (F1) > General > Appearance > Panel Layout.
Without using a library you can use eval
- the only time you should use. It's safer to use a library though.
eg...
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
alert('result:'+result+' count:'+count);
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
I've found that in the majority of cases doing block clauses on one line is a bad idea.
It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python.
In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension:
newlist = [splitColon.split(a) for a in someList]
although unless you need a reusable list specifically you may want to consider using a generator instead
listgen = (splitColon.split(a) for a in someList)
note the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use.
There is also a built in ternary operator in modern versions of python that allow you to do things like
string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print
or
iterator = max_value if iterator > max_value else iterator
Some people may find these more readable and usable than the similar if (condition):
block.
When it comes down to it, it's about code style and what's the standard with the team you're working on. That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.
myvariable = 4
mystring = str(myvariable) # '4'
also, alternatively try repr:
mystring = repr(myvariable) # '4'
This is called "conversion" in python, and is quite common.
If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".
Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."
My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.
As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.
It seems that you have to either use a big amount of code to simulate hashes in bash to get linear behavior or stick to the quadratic superlinear versions.
Among those versions, saua's solution is the best (and simplest):
sort -n ip_addresses.txt | uniq -c
I found http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-11/0118.html. But it's ugly as hell...
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
answer[k++] = a[i] < b[j] ? a[i++] : b[j++];
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
Is a little bit more compact but exactly the same!
There is no automatic addition of app.config file when you add a class library project to your solution.
To my knowledge, there is no counter indication about doing so manualy. I think this is a common usage.
About log4Net config, you don't have to put the config into app.config, you can have a dedicated conf file in your project as well as an app.config file at the same time.
this link http://logging.apache.org/log4net/release/manual/configuration.html will give you examples about both ways (section in app.config and standalone log4net conf file)
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
You cannot style a variable such as $ip['countryName']
You can only style elements like p,div, etc, or classes and ids.
If you want to style $ip['countryName'] there are several ways.
You can echo it within an element:
echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';
If you want to style both the variables the same style, then set a class like:
echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';
You could also embed the variables within your actual html rather than echoing them out within the code.
$city = $ip['cityName'];
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>
Make sure that your sas.png
is marked as Build Action: Content
and Copy To Output Directory: Copy Always
in its Visual Studio Properties
...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext
is string
path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image
would be automatically loaded at runtime.
In my current application, I'm doing both. When the user identifies an image to attach to a record, I use ImageMagick to resize it to an appropriate size for display on screen (about 300x300 for my application) and store that in the database for ease of access, but then also copy the user's original file to a network share so that it's available for applications that require higher resolution (like printing).
(There are a couple other factors involved as well: Navision will only display BMPs, so when I resize it I also convert to BMP for storage, and the database is replicated to remote sites where it's useful to be able to display the image. Printing is only done at the head office, so I don't need to replicate the original file.)
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:
from __future__ import print_function # In python 2.7
import sys
@app.route('/button/')
def button_clicked():
print('Hello world!', file=sys.stderr)
return redirect('/')
Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post
Had your first code been bug free, my best guess is, it would have been how you do this job in JS. I mean;
splice
to perform your insertion.This is almost always 2x faster than a top down or bottom up linear search and insert as mentioned in domoarigato's answer which i liked very much and took it as a basis to my benchmark and finally push
and sort
.
Of course under many cases you are probably doing this job on some objects in real life and here i have generated a benchmark test for these three cases for an array of size 100000 holding some objects. Feel free to play with it.
there are two projects that allow an "obvious" transition between python objects and javascript objects, with "obvious" translations from int or float to Number and str or unicode to String: PyV8 and, as one writer has already mentioned: python-spidermonkey.
there are actually two implementations of pyv8 - the original experiment was by sebastien louisel, and the second one (in active development) is by flier liu.
my interest in these projects has been to link them to pyjamas, a python-to-javascript compiler, to create a JIT python accelerator.
so there is plenty out there - it just depends what you want to do.
An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.
The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080
), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host
) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).
They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.
Just because it’s a really useful paper, here are some other figures. Please download it for full access.
Taking a look at Disk I/O:
Now looking at CPU overhead:
Now some examples of memory (read the paper for details, memory can be extra tricky):
Though this is an old question, I've been looking for this. Here's my compilation of some solutions answered here and some other ideas found elsewhere to get a one-size-fits-all solution.
CODE :
// Post to browser console
function console($data, $is_error = false, $file = false, $ln = false) {
if(!function_exists('console_wer')) {
function console_wer($data, $is_error = false, $bctr, $file, $ln) {
echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); }); }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
}
}
return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
}
//PHP Exceptions handler
function exceptions_to_console($svr, $str, $file, $ln) {
if(!function_exists('severity_tag')) {
function severity_tag($svr) {
$names = [];
$consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
foreach ($consts as $code => $name) {
if ($svr & $code) $names []= $name;
}
return join(' | ', $names);
}
}
if (error_reporting() == 0) {
return false;
}
if(error_reporting() & $svr) {
console(severity_tag($svr).' : '.$str, true, $file, $ln);
}
}
// Divert php error traffic
error_reporting(E_ALL);
ini_set("display_errors", "1");
set_error_handler('exceptions_to_console');
TESTS & USAGE :
Usage is simple. Include first function for posting to console manually. Use second function for diverting php exception handling. Following test should give an idea.
// Test 1 - Auto - Handle php error and report error with severity info
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (Exception $e) {
echo "jsdlkjflsjfkjl";
}
// Test 2 - Manual - Without explicitly providing file name and line no.
console(array(1 => "Hi", array("hellow")), false);
// Test 3 - Manual - Explicitly providing file name and line no.
console(array(1 => "Error", array($some_result)), true, 'my file', 2);
// Test 4 - Manual - Explicitly providing file name only.
console(array(1 => "Error", array($some_result)), true, 'my file');
EXPLANATION :
The function console($data, $is_error, $file, $fn)
takes string or array as first argument and posts it on console using js inserts.
Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false.
Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace()
to fetch them for us.
Next function exceptions_to_console($svr, $str, $file, $ln)
has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code)
to provide more info on error.
NOTICE :
Above code uses JS functions and methods that are not available in older browsers. For compatibility with older versions, it needs replacements.
Above code is for testing environments, where you alone have access to the site. Do not use this in live (production) websites.
SUGGESTIONS :
First function console()
threw some notices, so I've wrapped them within another function and called it using error control operator '@'. This can be avoided if you didn't mind the notices.
Last but not least, alerts popping up can be annoying while coding. For this I'm using this beep (found in solution : https://stackoverflow.com/a/23395136/6060602) instead of popup alerts. It's pretty cool and possibilities are endless, you can play your favorite tunes and make coding less stressful.
This works for me
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setRequestProperty("Authorization", "basic " +
Base64.encode("username:password".getBytes()));
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
Because I wanted conversion to plain text with LF and bullets, I found this pretty solution on codeproject, which covers many conversion usecases:
Yep, looks so big, but works fine.
#find command in linux def : find command used to locate /search files in unix /linux system , find search for files in a directory hierarchy
1)exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir 2)-options -H =do not follow symoblic links while except while procesing . -L = follow symbolic links -P =never follow symbolic links -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) -Delete Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete #fails, find's exit status will be nonzero (when it eventually exits). find /home/mohan/a -mindepth 3 -maxdepth 3 -type f -name "*.txt" |xargs rm -rf find -type d -name find -type f -Name find /path/ -type f -iname (i is case insenstive) #find directores a/b/c and only delete c directory inside have "*.txt " find /home/mohan/a -mindepth 3 -maxdepth 3 -type f -name "*.txt" |xargs rm -rf find /home/mohan/a -mindepth 3 -maxdepath 3 -type f -name "*.txt" -delete #delete particular directory have empty file and only we can delete empty files find /home/mohan -type f -name "*.txt" -empty -DELETE #find multiple files and also find empty files find /home/mohan -type f \( -name "*.sh" -o -name "*.txt" \) -empty #delete empty files two or more Files find /home/mohan -type f \( -nmae "*.sh" -o -name "*.txt" \) -empty -delete #How to append contents of multiple files into one file find . -type f -name '*.txt' -exec cat {} + >> output.file #last modified files finding using less than 1 min (-n) ls -lrth|find . -type f -mmin -1 #last modified files more than 1 min (+n) ls -lrth|find . -type f -mmin +1 #last modified files exactly one mins find . -type f -mmin 1 last modifiedfiles exactly in one day by using command (-mtime) find . -type f -mtime 10 #last modified more than 10 days find . -type f -mtime +10 #last modified less than 10 days find . -type f -mtime -10 #How to Find Modified Files and Folders Starting from a Given Date to the Latest Date find . -type f -newermt "17-11-2020" #How to Find a List of “sh” Extension Files Accessed in the Last 30 Days--- -matdimtype ls -lrt|find . -type f -iname ".sh" -atime -30 #How to Find a List of Files Created Today, -1 means less than min, ls -lrt | find . -type f -ctime -1 -ls
Your file .idea/workspace.xml
is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)
You can verify it using following git command, that lists all ignored files:
git ls-files --others -i --exclude-standard
This is what I normally use, albeit a bit manual:
/* Add a 'temporary' UDDT with the new definition */
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL
/* Build a command to alter all the existing columns - cut and
** paste the output, then run it */
select 'alter table dbo.' + TABLE_NAME +
' alter column ' + COLUMN_NAME + ' t_myudt_tmp'
from INFORMATION_SCHEMA.COLUMNS
where DOMAIN_NAME = 't_myudt'
/* Remove the old UDDT */
exec sp_droptype t_mydut
/* Rename the 'temporary' UDDT to the correct name */
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE'
AngularJS with Bootstrap UI Tolltip (uib-tooltip), has three versions of tool-tip:
uib-tooltip, uib-tooltip-template and uib-tooltip-html
- uib-tooltip takes only text and will escape any HTML provided
- uib-tooltip-html takes an expression that evaluates to an HTML string
- uib-tooltip-template takes a text that specifies the location of the template
In my case, I opted for uib-tooltip-html and there are three parts to it:
Example:
(function(angular) {
//Step 1: configure $sceProvider - this allows the configuration of $sce service.
angular.module('myApp', ['uib.bootstrap'])
.config(function($sceProvider) {
$sceProvider.enabled(false);
});
//Step 2: Set the tooltip content in the controller
angular.module('myApp')
.controller('myController', myController);
myController.$inject = ['$sce'];
function myController($sce) {
var vm = this;
vm.tooltipContent = $sce.trustAsHtml('I am the first line <br /><br />' +
'I am the second line-break');
return vm;
}
})(window.angular);
//Step 3: Use the tooltip in HTML (UI)
<div ng-controller="myController as get">
<span uib-tooltip-html="get.tooltipContent">other Contents</span>
</div>
For more information, please check here
If you need something quick and dirty, you can just use PayPal's "Buy" buttons and drop them on your pages. These will take people off-site to PayPal where they can pay with a PayPal account or a credit card. This is free and super easy to implement.
If you want something a bit nicer where people pay on-site with their credit card, then you would want to look into one of those 3rd part payment providers. None of them (that I'm aware of) are completely free. All will have a per-transaction fee, and most will have a monthly fee as well.
Personally I've worked with Authorize.NET and PayPal Website Payments Pro. Both have great APIs and sample code that you can hook into via PHP easily enough.
I was looking at cutting out SNS until I saw this in the Lambda client docs (Java version):
Client for accessing AWS Lambda. All service calls made using this client are blocking, and will not return until the service call completes.
So SNS has an obvious advantage: it's asynchronous. Your lambda won't wait for the subsequent lambda to complete.
use this function derived from link provided by IJas
function openFbPopUp() {
var fburl = '';
var fbimgurl = 'http://';
var fbtitle = 'Your title';
var fbsummary = "your description";
var sharerURL = "http://www.facebook.com/sharer/sharer.php?s=100&p[url]=" + encodeURI(fburl) + "&p[images][0]=" + encodeURI(fbimgurl) + "&p[title]=" + encodeURI(fbtitle) + "&p[summary]=" + encodeURI(fbsummary);
window.open(
sharerURL,
'facebook-share-dialog',
'width=626,height=436');
return false;
}
Or you can also use the latest FB.ui Function if using FB JavaScript SDK for more controlled callback function.
refer: FB.ui
function openFbPopUp() {
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
Since the getTime function of the Date object gets the milliseconds since 1970/01/01, we can do this:
var time = '12:23:00';
var seconds = new Date('1970-01-01T' + time + 'Z').getTime() / 1000;
If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:
netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672
for the remote access.
Just my couple cents... sometimes it's good to be sure there are no any duplicates... so we have the next function in the utils library:
jQuery.loadCSS = function(url) {
if (!$('link[href="' + url + '"]').length)
$('head').append('<link rel="stylesheet" type="text/css" href="' + url + '">');
}
How to use:
$.loadCSS('css/style2.css');
Use the traceback module:
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
print('An error occurred on line {} in statement {}'.format(line, text))
exit(1)
Solution suggested by Prashant worked fine for me.
Tomcat9 Properties > Configure > Startup > Mode = Java Tomcat9 Properties > Configure > Shutdown > Mode = Java
It is better to use HastSet
1-a) A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here
1-b) HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operation are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference.Take a look here
2) There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.
The HashSet class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.
The only catch of HashSet is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet into a List and iterate through that.Take a look here
Make sure your apache .conf files are correct -- then double check your .htaccess files. In this case, my .htaccess were incorrect! I removed some weird stuff no longer needed and it worked. Tada.
To ensure easy and correct installation for python use pip from the get go
To install pip:
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2 get-pip.py # for python 2.7
$ sudo python3 get-pip.py # for python 3.x
To install scipy using pip:
$ pip2 install scipy # for python 2.7
$ pip3 install scipy # for python 3.x
With the nuget package System.Resources.ResourceManager
(v4.3.0) the ResourceSet
and ResourceManager.GetResourceSet
are not available.
Using the ResourceReader
, as this post suggest: "C# - Cannot getting a string from ResourceManager (from satellite assembly)"
It's still possible to read the key/values of the resource file.
System.Reflection.Assembly resourceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("YourAssemblyName"));
String[] manifests = resourceAssembly.GetManifestResourceNames();
using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream(manifests[0])))
{
System.Collections.IDictionaryEnumerator dict = reader.GetEnumerator();
while (dict.MoveNext())
{
String key = dict.Key as String;
String value = dict.Value as String;
}
}
You can try the following solution to change the size of custom checkbox
by setting the following properties to Checkbox
in your layout file. Worked for me
android:scaleX="0.8" android:scaleY="0.8"
android:button="@null"
android:scaleX="0.8"
android:scaleY="0.8"
android:background="@drawable/custom_checkbox"
add following lines to drawable file
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false"
android:drawable="@drawable/unchecked_img" />
<item android:state_checked="true"
android:drawable="@drawable/checked_img" />
</selector>
This is not exactly the answer to the question, but I end up here every time I want to find out how to get my batch file to exit with and error code when a process returns an nonzero code.
So here is the answer to that:
if %ERRORLEVEL% NEQ 0 exit %ERRORLEVEL%
On small device : 4 columns x 3 (= 12) ==> col-sm-3
On extra small : 3 columns x 4 (= 12) ==> col-xs-4
<footer class="row">
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 4</li>
<li>Text 5</li>
<li>Text 6</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 7</li>
<li>Text 8</li>
<li>Text 9</li>
</ul>
</nav>
<nav class="hidden-xs col-sm-3">
<ul class="list-unstyled">
<li>Text 10</li>
<li>Text 11</li>
<li>Text 12</li>
</ul>
</nav>
</footer>
As you say, hidden-xs is not enough, you have to combine xs and sm class.
Here is links to the official doc about available responsive classes and about the grid system.
Have in head :
Unfortunately, the accepted answer doesn't work for me (I'm using GitHub flavoured markdown).
It occurs to me since we're adding HTML elements, why not just add an <input>
instead.
| demo | demo |
| ------------------------------------------------- | ---- |
| <input type="checkbox" disabled checked /> works | |
| <input type="checkbox" disabled /> works here too | |
This should work in any environment cuz it's plain HTML (see FYI below).
FYI, this example was tested in VS Code markdown preview mode(GitHub flavoured), the screenshot is also taken in VS Code preview mode, It's not exactly working on GitHub.
Emoji mentioned above is a good alternative, if this doesn't work in your target environment.
Try this. Works fine in ICS. If You want to stop service simply click the notification generated in statusbar.
public class HUD extends Service
{
protected boolean foreground = false;
protected boolean cancelNotification = false;
private Notification notification;
private View myView;
protected int id = 0;
private WindowManager wm;
private WindowManager.LayoutParams params;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// System.exit(0);
Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_SHORT).show();
params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
params.gravity=Gravity.TOP|Gravity.LEFT;
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
inflateview();
foregroundNotification(1);
//moveToForeground(1,n,true);
}
@Override
public void onDestroy() {
super.onDestroy();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(0);
Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_SHORT).show();
if(myView != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(myView);
myView = null;
}
}
protected Notification foregroundNotification(int notificationId)
{
notification = new Notification(R.drawable.ic_launcher, "my Notification", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;
notification.setLatestEventInfo(this, "my Notification", "my Notification", notificationIntent());
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(id, notification);
return notification;
}
private PendingIntent notificationIntent() {
Intent intent = new Intent(this, stopservice.class);
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pending;
}
public void inflateview()
{
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.activity_button, null);
myView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getBaseContext(),"onToasttt", Toast.LENGTH_SHORT).show();
return false;
}
});
// Add layout to window manager
wm.addView(myView, params);
}
}
UPDATE
Sample here
To create an overlay view, when setting up the LayoutParams DON'T set the type to TYPE_SYSTEM_OVERLAY.
Instead set it to TYPE_PHONE.
Use the following flags:
FLAG_NOT_TOUCH_MODAL
FLAG_WATCH_OUTSIDE_TOUCH
go get github.com/mattn/sudo
Then
sudo Example1Server.exe
An old post but here is how I handled it. Using newms87's method:
if($action == "redemption")
{
if($redemptionId != "")
{
$results = json_decode($rewards->redeemPoints($redemptionId));
if($results->success == true)
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
// put results in session and redirect back to same page passing an action paraameter
$_SESSION['post_data'] = json_encode($results);
header("Location:" . $redirectLocation);
exit();
}
}
}
elseif($action == "redemptionComplete")
{
// if data is in session pull it and unset it.
if(isset($_SESSION['post_data']))
{
$results = json_decode($_SESSION['post_data']);
unset($_SESSION['post_data']);
}
// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
else
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
header("Location:" . $redirectLocation);
}
}
Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
using (var httpClient = new HttpClient(httpClientHandler))
{
var httpResponse = httpClient.GetAsync("https://example.com").Result;
}
}
Original source:
The easiest way is
https://graph.facebook.com/me?fields=id&access_token="xxxxx"
then you will get json response which contains only userid.
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
You can use it with your local variables, like this:
@animal = "Dog"
@action = "licks"
@second_animal = "Bird"
"The #{@animal} #{@action} the #{@second_animal}"
the output would be: "The Dog licks the Bird"
Be careful with Backslashes, don't forget them (neither use twice:)
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
I had the same issue.. I thought I had branch named foo
when I try to:
git checkout foo
I was getting:
error: pathspec 'foo' did not match any file(s) known to git.
Then I tried the full branch name:
git checkout feature/foo
then worked for me.
Note that the use of unescape()
is deprecated and doesn't work with the TypeScript compiler, for example.
Based on radicand's answer and the comments section below, here's an updated solution:
var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));
http://example.com
I posted what I use to solve this very issue efficiently here using a quick Binary Search Algorithm: https://stackoverflow.com/a/52786742/1678210
I didn't want to copy the same answer. Someone else had asked it slightly differently but the answer is the same.
document.onkeypress = function(event){
alert(event.key)
}
Faced with this issue when determining an environment, I came up with the following one-liner:
string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));
That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null
. This could easily be amended to return a different value.
It's not strictly a switch, more a cascading if statement but it's neat and it worked.
autoconf
and automake
:configure
, make
and sudo make install
:./configure # Creates Makefile (from Makefile.in).
make # Creates the application (from the Makefile just created).
sudo make install # Installs the application
# Often, by default its files are installed into /usr/local
Notation below is roughly: inputs --> programs --> outputs
DEVELOPER runs these:
configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in
depreciated. Use configure.ac)
Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)
INSTALLER runs these:
Makefile.in -> configure -> Makefile (*.in = input file)
Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)
"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."
"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."
Manuals:
GNU AutoTools (The definitive manual on this stuff)
m4 (used by autoconf)
Free online tutorials:
The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)
From this my generated configure is over 41k lines of code.
And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)
(Too many answers are redundant and outdated.) The best solution now is this:
history.replaceState(null, null, ' ');
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{
@Autowired
MyService service;
...
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException
{
// Do something with the context here
}
}
you can also use Boost.
boost::filesystem::exists( filename );
it works for files and folders.
And you will have an implementation close to something ready for C++14 in which filesystem should be part of the STL (see here).
var postData = "text";
$.ajax({
type: "post",
url: "url",
data: postData,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
I resorted to adding Analytics via cocoa pods again and disabled bit code for now.
Hopefully a future cocoa pods version will support it.
my two cents worth ~
Cloud refers to an (imaginary/easily scalable) unlimited space and processing power. The term shields the underlying technologies and highlights solely its unlimited storage-space and power.
Grid is a group of physically close-by machines setup. Term usually imply the processing power (ie:MFLOPS/GFLOPS), referred by engineers
Cluster is a set of logically connected machines/device (like a clusters of harddisk, cluster of database). Term highlights how devices are able to connect together and operate as a unit, referred by engineers
BeanUtils will only copy public fields and is a bit slow. Instead go with getter and setter methods.
public Object loadData (RideHotelsService object_a) throws Exception{
Method[] gettersAndSetters = object_a.getClass().getMethods();
for (int i = 0; i < gettersAndSetters.length; i++) {
String methodName = gettersAndSetters[i].getName();
try{
if(methodName.startsWith("get")){
this.getClass().getMethod(methodName.replaceFirst("get", "set") , gettersAndSetters[i].getReturnType() ).invoke(this, gettersAndSetters[i].invoke(object_a, null));
}else if(methodName.startsWith("is") ){
this.getClass().getMethod(methodName.replaceFirst("is", "set") , gettersAndSetters[i].getReturnType() ).invoke(this, gettersAndSetters[i].invoke(object_a, null));
}
}catch (NoSuchMethodException e) {
// TODO: handle exception
}catch (IllegalArgumentException e) {
// TODO: handle exception
}
}
return null;
}
In STS/Eclipse go to "project explorer" or "package explorer" and
there is a folder called "server." Open it and you will find server.xml
file. Inside this file at the bottom you find a definition like
<Context docBase="myproject" path="/myproject" reloadable="true"
source="org.eclipse.jst.jee.server:myproject"/>
You might find duplicates of the same definition that you would need to remove.
You just try this, Its so easy
<script>
$("#YourDropDownId").change(function () {
alert($("#YourDropDownId").val());
});
</script>
Use the property table-layout:fixed;
on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.
<table style='table-layout:fixed;'>
<tbody>
<tr>
<td>gobble de gook</td>
<td>mibs</td>
</tr>
</tbody>
</table>
Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>
, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.
In the Windows command prompt you can disable tab completion, by launching it thusly:
cmd.exe /f:off
Then the tab character will be echoed to the screen and work as you expect. Or you can disable the tab completion character, or modify what character is used for tab completion by modifying the registry.
The cmd.exe
help page explains it:
You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar and/or HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.
If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.
The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the "~" and "/" characters at the front of the path so your examples above should work.
I noticed your examples use the path "~/Account/myPartial.ascx", but you mentioned that your user control is in the Views/Account folder. Have you tried
<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>
or is that just a typo in your question?
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:
Option1:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
Option2:
SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson();
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();
Option 2 is twice quicker than option 1
The option 2 inconvenience is that you have to make specific code for read:
Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);
Sub
don't return values and function
s don't have side effects.
Sometimes you want both side effect and return value.
This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:
Sub getValue(retValue as Long)
...
retValue = 42
End SUb
Sub Main()
Dim retValue As Long
getValue retValue
...
End SUb
I'm sorry, but upgrading development station to SSD and tons of ram has probably a bigger influence than points below combined.
Increasing build performance has major priority for the development teams, so make sure you are using latest Gradle and Android Gradle Plugin.
Create a file named gradle.properties
in whatever directory applies:
/home/<username>/.gradle/
(Linux)/Users/<username>/.gradle/
(Mac)C:\Users\<username>\.gradle
(Windows)Append:
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.krd1mm27v
org.gradle.jvmargs=-Xmx5120m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true
# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true
# Set to true or false to enable or disable the build cache.
# If this parameter is not set, the build cache is disabled by default.
# http://tools.android.com/tech-docs/build-cache
android.enableBuildCache=true
Gradle properties works local if you place them at projectRoot\gradle.properties
and globally if you place them at user_home\.gradle\gradle.properties
. Properties applied if you run gradle tasks from console or directly from idea:
It is possible to tweak Gradle-IntelliJ integration from the IDE settings GUI. Enabling "offline work" (check answer from yava below) will disable real network requests on every "sync gradle file".
One of the slowest steps of the apk build is converting java bytecode into single dex file. Enabling native multidex (minSdk 21 for debug builds only) will help the tooling to reduce an amount of work (check answer from Aksel Willgert below).
Prefer @aar
dependencies over library sub-projects.
Search aar package on mavenCentral, jCenter or use jitpack.io to build any library from github. If you are not editing sources of the dependency library you should not build it every time with your project sources.
Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security (don't try this at home!). But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular AndroidStudio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related.
Gradle has built-in support for profiling projects. Different projects are using a different combination of plugins and custom scripts. Using --profile
will help to find bottlenecks.
Once you have connected your UITableView delegate
and datasource
to your controller, you could do something like this:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *sectionName;
switch (section) {
case 0:
sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
break;
case 1:
sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
break;
// ...
default:
sectionName = @"";
break;
}
return sectionName;
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionName: String
switch section {
case 0:
sectionName = NSLocalizedString("mySectionName", comment: "mySectionName")
case 1:
sectionName = NSLocalizedString("myOtherSectionName", comment: "myOtherSectionName")
// ...
default:
sectionName = ""
}
return sectionName
}
Updated based on Muhammad's answer...
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(headers()['Content-Range']);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
With the pandas
library, this is as easy as using two commands!
pandas.read_json()
To convert a JSON string to a pandas object (either a series or dataframe). Then, assuming the results were stored as df
:
df.to_csv()
Which can either return a string or write directly to a csv-file.
Based on the verbosity of previous answers, we should all thank pandas for the shortcut.
Yes. They are different file formats (and their file extensions).
Wikipedia entries for each of the formats will give you quite a bit of information:
Image formats can be separated into three broad categories:
Uncompressed formats take up the most amount of data, but they are exact representations of the image. Bitmap formats such as BMP generally are uncompressed, although there also are compressed BMP files as well.
Lossy compression formats are generally suited for photographs. It is not suited for illustrations, drawings and text, as compression artifacts from compressing the image will standout. Lossy compression, as its name implies, does not encode all the information of the file, so when it is recovered into an image, it will not be an exact representation of the original. However, it is able to compress images very effectively compared to lossless formats, as it discards certain information. A prime example of a lossy compression format is JPEG.
Lossless compression formats are suited for illustrations, drawings, text and other material that would not look good when compressed with lossy compression. As the name implies, lossless compression will encode all the information from the original, so when the image is decompressed, it will be an exact representation of the original. As there is no loss of information in lossless compression, it is not able to achieve as high a compression as lossy compression, in most cases. Examples of lossless image compression is PNG and GIF. (GIF only allows 8-bit images.)
TIFF and BMP are both "wrapper" formats, as the data inside can depend upon the compression technique that is used. It can contain both compressed and uncompressed images.
When to use a certain image compression format really depends on what is being compressed.
Related question: Ruthlessly compressing large images for the web
I don't know ASP.NET very well, but can you use the ternary operator?
http://en.wikipedia.org/wiki/Ternary_operation
Something like: (x=Eval("item")) == Null ? 0 : x
I finally found the problem. The error was not the good one.
Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
Strange Bug, Hope it will help other people.
Socket is SW abstraction of networking endpoint, used as the interface to the application. In Java, C# it is represented by object, in Linux, Unix it is a file.
Port is just a property of a socket you have specify if you want to establish a communication. To receieve packet from a socket you have to bind it to specific local port and NIC (with local IP address) or all NICs (INADDR_ANY is specified in the bind call). To send packet, you have to specify port and IP of the remote socket.
If you have to use setRequestedOrientation()
, there is no way but sacrifice the windowIsTranslucent attribute on Android 8.0
values\styles.xml
for api level 25- (<8.0)
<style name="Base.Theme.DesignDemo" parent="Base.Theme.AppCompat.Light">
...
<item name="android:windowIsTranslucent">true</item>
...
</style>
values-v26\styles.xml
for api level 26 (=8.0)
<style name="Base.Theme.DesignDemo" parent="Base.Theme.AppCompat.Light">
...
<!-- android 8.0(api26),Only fullscreen opaque activities can request orientation -->
<item name="android:windowIsTranslucent">false</item>
...
</style>
values-v27\styles.xml
for api level 27+ (>8.0)
<style name="Base.Theme.DesignDemo" parent="Base.Theme.AppCompat.Light">
...
<item name="android:windowIsTranslucent">true</item>
...
</style>
Not very clear what your issue is, but it sounds like you want something like this:
List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );
if( printer.Exists( p => p.Equals( "jupiter" ) ) )
{
...
}
Make sure your app_offline.htm file is at least 512 bytes long. A zero-byte app_offline.htm will have no effect.
UPDATE: Newer versions of ASP.NET/IIS may behave better than when I first wrote this.
UPDATE 2: If you are using ASP.NET MVC, add the following to web.config:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
sh -c 'cd /c && ../a/helloworld'
Another possibility: When you created the user, you may have accidentally been use
ing a database other than admin
, or other than the one you wanted. You need to set --authenticationDatabase
to the database that the user was actually created under.
mongodb
seems to put you in the test
database by default when you open the shell, so you'd need to write --authenticationDatabase test
rather than --authenticationDatabase admin
if you accidentally were use
ing test
when you ran db.createUser(...)
.
Assuming you have access to the machine that's running the mongodb instance, y could disable authorization in /etc/mongod.conf
(comment out authorization
which is nested under security), and then restart your server, and then run:
mongo
show users
And you might get something like this:
{
"_id" : "test.myusername",
"user" : "myusername",
"db" : "test",
"roles" : [
{
"role" : "dbOwner",
"db" : "mydatabasename"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
Notice that the db
value equals test
. That's because when I created the user, I didn't first run use admin
or use desiredDatabaseName
. So you can delete the user with db.dropUser("myusername")
and then create another user under your desired database like so:
use desiredDatabaseName
db.createUser(...)
Hopefully that helps someone who was in my position as a noob with this stuff.
Maybe it does not fit every use case, but
<input type="range" min="0" max="10" />
can do a fine job: fiddle.
Check the documentation.
Both algorithms (AES and twofish) are considered very secure. This has been widely covered in other answers.
However, since AES is much widely used now in 2016, it has been specifically hardware-accelerated in several platforms such as ARM and x86. While not significantly faster than twofish before hardware acceleration, AES is now much faster thanks to the dedicated CPU instructions.
I handle validation exceptions in Laravel 5.3 like this. If you use Laravel Collective it will automatically display errors next to inputs and if you use laracasts/flash it will also show first validation error as a notice.
Handler.php
render:
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Validation\ValidationException) {
return $this->handleValidationException($request, $e);
}
(..)
}
And the function:
protected function handleValidationException($request, $e)
{
$errors = @$e->validator->errors()->toArray();
$message = null;
if (count($errors)) {
$firstKey = array_keys($errors)[0];
$message = @$e->validator->errors()->get($firstKey)[0];
if (strlen($message) == 0) {
$message = "An error has occurred when trying to register";
}
}
if ($message == null) {
$message = "An unknown error has occured";
}
\Flash::error($message);
return \Illuminate\Support\Facades\Redirect::back()->withErrors($e->validator)->withInput();
}
This works for me:
<a href="" ng-click="doSomething($event)">Action</a>
this.doSomething = function($event) {
$event.stopPropagation();
$event.preventDefault();
};
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
Auto reload with target of your choice. In this case target is _self
set to itself,but you could change the reload page by simply changing the window.open('self.location', '_self');
code to something like this examplewindow.top.location="window.open('http://www.YourPageAdress.com', '_self'";
.
With a confirmation ALERT message:
<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}
function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}
function alert_idle() {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
reset_interval();
}
else{
auto_logout();
}
}
function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>
Without confirmation alert:
<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
}
function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
}
function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>
Body code is the SAME for both solutions:
<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">
Will be slightly neater using a CSS class instead of repeating inline styles.
CSS
input[type=submit] {
position: absolute;
left: -9999px;
}
HTML
<form ng-submit="myFunc()">
<input type="text" ng-model="name" />
<br />
<input type="text" ng-model="email" />
<input type="submit" />
</form>
One thing that just bit me was setting the -density
AFTER the input file name. That didn't work. Moving it to the first option in convert (before anything else) made it work (for me, YMMV, etc).
Simplifying a bit, you can imagine map()
doing something like this:
def mymap(func, lst):
result = []
for e in lst:
result.append(func(e))
return result
As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. I said "simplifying a bit" because in reality map()
can process more than one iterable:
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.
For the second part in the question: What role does this play in making a Cartesian product? well, map()
could be used for generating the cartesian product of a list like this:
lst = [1, 2, 3, 4, 5]
from operator import add
reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))
... But to tell the truth, using product()
is a much simpler and natural way to solve the problem:
from itertools import product
list(product(lst, lst))
Either way, the result is the cartesian product of lst
as defined above:
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
(2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) { event.preventDefault(); $('div.link1').show(); //whatever else you want to do });
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) { event.preventDefault(); window.location = $(this).attr("url"); });
I made the same error using sudo for my installation. (oops)
brew install python
brew linkapps python
brew link --overwrite python
This brought everything back to normal.
I like doing something like this:
Message::select('*')
->from(DB::raw("( SELECT * FROM `messages`
WHERE `to_id` = ".Auth::id()." AND `isseen` = 0
GROUP BY `from_id` asc) as `sub`"))
->count();
It's not very elegant, but it's simple.
For obvious security reasons you can't set the value of a file input, even to an empty string.
All you have to do is reset the form where the field or if you only want to reset the file input of a form containing other fields, use this:
function reset_field (e) {
e.wrap('<form>').parent('form').trigger('reset');
e.unwrap();
}?
Here is an exemple: http://jsfiddle.net/v2SZJ/1/
I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error
The FLAWED version
import threading
import time
# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []
def add():
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output when ERROR
Exception in thread Thread-63:
Traceback (most recent call last):
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
l.remove(i)
ValueError: list.remove(x): x not in list
Version that uses locks
import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
with lock:
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
with lock:
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output
[] # Empty list
Conclusion
As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another
It is enough to use color property alongside with -webkit-text-fill-color this way:
input {_x000D_
color: red; /* color of caret */_x000D_
-webkit-text-fill-color: black; /* color of text */_x000D_
}
_x000D_
<input type="text"/>
_x000D_
Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.
The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN
So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.
if ( values > 0 ) {
//you got a positive value
}else{
//you got a negative or zero value
}
There is also a solution:
http://www.welefen.com/php-unicode-to-utf8.html
function entity2utf8onechar($unicode_c){
$unicode_c_val = intval($unicode_c);
$f=0x80; // 10000000
$str = "";
// U-00000000 - U-0000007F: 0xxxxxxx
if($unicode_c_val <= 0x7F){ $str = chr($unicode_c_val); } //U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
else if($unicode_c_val >= 0x80 && $unicode_c_val <= 0x7FF){ $h=0xC0; // 11000000
$c1 = $unicode_c_val >> 6 | $h;
$c2 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2);
} else if($unicode_c_val >= 0x800 && $unicode_c_val <= 0xFFFF){ $h=0xE0; // 11100000
$c1 = $unicode_c_val >> 12 | $h;
$c2 = (($unicode_c_val & 0xFC0) >> 6) | $f;
$c3 = ($unicode_c_val & 0x3F) | $f;
$str=chr($c1).chr($c2).chr($c3);
}
//U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x10000 && $unicode_c_val <= 0x1FFFFF){ $h=0xF0; // 11110000
$c1 = $unicode_c_val >> 18 | $h;
$c2 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c3 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c4 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4);
}
//U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x200000 && $unicode_c_val <= 0x3FFFFFF){ $h=0xF8; // 11111000
$c1 = $unicode_c_val >> 24 | $h;
$c2 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c3 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c4 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c5 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5);
}
//U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x4000000 && $unicode_c_val <= 0x7FFFFFFF){ $h=0xFC; // 11111100
$c1 = $unicode_c_val >> 30 | $h;
$c2 = (($unicode_c_val & 0x3F000000)>>24) | $f;
$c3 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c4 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c5 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c6 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5).chr($c6);
}
return $str;
}
function entities2utf8($unicode_c){
$unicode_c = preg_replace("/\&\#([\da-f]{5})\;/es", "entity2utf8onechar('\\1')", $unicode_c);
return $unicode_c;
}
You can try this:
#!/bin/bash
aws_instance=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
aws_region=$(wget -q -O- http://169.254.169.254/latest/meta-data/hostname)
aws_region=${aws_region#*.}
aws_region=${aws_region%%.*}
aws_zone=`ec2-describe-instances $aws_instance --region $aws_region`
aws_zone=`expr match "$aws_zone" ".*\($aws_region[a-z]\)"`
We can also define it using global
in setupTests
// setupTests.js
global.open = jest.fn()
And call it using global
in the actual test:
// yourtest.test.js
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
I usually use information_Schema.columns
and information_schema.tables
, although like @yuck said, sys.tables
and sys.columns
are shorter to type.
In a loop, concatenate these
@sql = @sql + 'select' + column_name +
' from ' + table_name +
' where ' + column_name ' like ''%''+value+''%' UNION
Then execute the resulting sql.
You can escape the apostrophe with a \
character as well:
mystring.replace('\'', '')
This issue is not because of corrupt database. I found the solution from this video - https://www.youtube.com/watch?v=MqOsp54EA3I
It is suggested to increase the values of two variables in php.ini file. Change following in php.ini
upload_max_filesize=64M
post_max_size=64M
Then restart the server.
This solved my issue. Hope solves yours too.
It depends on the reason why you're willing to exit node.js process, but in any case process.exit()
is the last option to consider. A quote from documentation:
It is important to note that calling
process.exit()
will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations toprocess.stdout
andprocess.stderr
.In most situations, it is not actually necessary to call
process.exit()
explicitly. The Node.js process will exit on it's own if there is no additional work pending in the event loop. Theprocess.exitCode
property can be set to tell the process which exit code to use when the process exits gracefully.
Let’s cover possible reasons why you might be willing to exit node.js process and why you should avoid process.exit()
:
If script has reached its end and node interpreter doesn't exit, it indicates that some async operations are still pending. It’s wrong to force process termination with process.exit()
at this point. It’s better to try to understand what is holding your script from exiting in expected way. And when you settle this, you can use process.exitCode
to return any result to calling process.
For example, if you’re willing to gracefully shut down an express app. Unlike command line script, express app keeps running infinitely, waiting for new requests. process.exit()
will be a bad option here because it’s going to interrupt all requests which are in pipeline. And some of them might be non-idempotent (UPDATE, DELETE). Client will never know if those requests are completed or not on server side and it might be the reason of data inconsistency between client and server. The only good solution is to tell http server to stop accepting new requests and wait for pending ones to finish with server.close()
:
var express = require('express');
var app = express();
var server = app.listen(80);
process.on( 'SIGTERM', function () {
server.close(function () {
console.log("Finished all requests");
});
});
If it still doesn't exit - see Case 1.
It's always better to throw
an error, you’ll get a nicely formatted stack trace and error message. Upper levels of code can always decide if they can handle error (catch
) or let it crash the process. On the other side, process.exit(1)
will terminate process silently and there will be no chance to recover from this. It might be the only “benefit” of process.exit()
, you can be sure that process will be terminated.
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
In simple word export means letting the script we wrote to be used by another script. If we say export, we mean any module can use this script by importing it.
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
You can use 'th:if' together with 'th:text'
<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>
My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.
I was getting ó in $mail->Subject /w PHPMailer.
So for me the complete solution is:
// Your Subject with tildes. Example.
$someSubjectWithTildes = 'Subscripción España';
$mailer->CharSet = 'UTF-8';
$mailer->Encoding = 'quoted-printable';
$mailer->Subject = html_entity_decode($someSubjectWithTildes);
Hope it helps.
Try to place a
return 0;
on the end of your code or just erase the
void
from your main function I hope that I helped
When I want to display an empty date value I do this
if (sStrDate != "")
{
dateCreated.Value = DateTime.Parse(sStrDate);
}
else
{
dateCreated.CustomFormat = " ";
dateCreated.Format = DateTimePickerFormat.Custom;
}
Then when the user clicks on the control I have this:
private void dateControl_MouseDown(object sender, MouseEventArgs e)
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Long;
}
This allows you to display and use an empty date value, but still allow the user to be able to change the date to something when they wish.
Keep in mind that sStrDate has already been validated as a valid date string.
A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":
e.g. to flatten all but the last dimension:
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
Compiling your C program using Cygwin
We will be using the gcc compiler on Cygwin to compile programs.
1) Launch Cygwin
2) Change to the directory you created for this class by typing
cd c:/windows/desktop
3) Compile the program by typing
gcc myProgram.c -o myProgram
the command gcc invokes the gcc compiler to compile your C program.
I wrote a simple CSS compatible with Bootstrap to create full width and height tables:
Fiddle : https://jsfiddle.net/uasbfc5e/4/
The principle is :
The HTML :
<div class="tablefull">
<div class="tableheader">
<div class="col-xs-4">Header A</div>
<div class="col-xs-4">B</div>
<div class="col-xs-4">C</div>
</div>
<div>
<div class="col-xs-6">Content 50% width auto height</div>
<div class="col-xs-6">Hello World</div>
</div>
<div>
<div class="col-xs-9">Content 70% width auto height</div>
<div class="col-xs-3">Merry Halloween</div>
</div>
</div>
The CSS:
div.tablefull {
display: table;
table-layout: fixed;
width: 100%;
height: 100%;
}
div.tablefull>div.tableheader, div.tablefull>div.tableheader>div{
height: 0%;
}
div.tablefull>div {
display: table-row;
}
div.tablefull>div>div {
display: table-cell;
height: 100%;
padding: 0;
}
To rename a directory or file (I don't know much about complex cases, so there might be some caveats):
git filter-repo --path-rename OLD_NAME:NEW_NAME
To rename a directory in files that mention it (it's possible to use callbacks, but I don't know how):
git filter-repo --replace-text expressions.txt
expressions.txt
is a file filled with lines like literal:OLD_NAME==>NEW_NAME
(it's possible to use Python's RE with regex:
or glob with glob:
).
To rename a directory in messages of commits:
git-filter-repo --message-callback 'return message.replace(b"OLD_NAME", b"NEW_NAME")'
Python's regular expressions are also supported, but they must be written in Python, manually.
If the repository is original, without remote, you will have to add --force
to force a rewrite. (You may want to create a backup of your repository before doing this.)
If you do not want to preserve refs (they will be displayed in the branch history of Git GUI), you will have to add --replace-refs delete-no-add
.
This doesn't exactly answer the question as posed, but it does create the same visual effect that you are trying to achieve.
<style>
body {
border:0;
padding:0;
margin:0;
padding-top:60px;
}
#header {
position:absolute;
top:0;
height:60px;
width:100%;
}
#wrapper {
height:100%;
width:100%;
}
</style>
The R packages dplyr and sf import the operator %>% from the R package magrittr.
Help is available by using the following command:
?'%>%'
Of course the package must be loaded before by using e.g.
library(sf)
The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)
int space = 40;
printf("%*s", space, "Hello");
This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows:
printf("%*d", space, 10);
printf("%*c", space, 'x');
This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:
printf("%*d", 10, 10);
printf("%*c", 20, 'x');
printf("%*s", 30, "Hello");
Hope this helps someone like me in future.