i got the same issue, i updated the hosts file with the server address and it worked
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..
java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.
I was also facing the same problem. To fix this to the following steps.
Copy-paste the following into your current terminal:
gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"
This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
I had same issue, and for me, I was trying to use an IP Address instead of computer name. Just adding this as one more potential solution for people finding this down the road.
First find the condition that occurs in all situations, then filter the special conditions:
$('[myc="blue"]')
.filter('[myid="1"],[myid="3"]');
None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:
setx YOUR_VAR "VALUE"
You can access it in your scripts using os.environ['YOUR_VAR']
.
A little late to the party, but since I was looking for it (and I might need to find it again sometime), here's what I did to include version, company name, etc. into my C++ DLL under VS2013 Express:
Hope this helps!
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
Have a look at CASE statements
http://msdn.microsoft.com/en-us/library/ms181765.aspx
I've tried to create a utils class for this, so any activity or fragment can implement this to be simpler.
The code was written with Kotlin & has Java-interop as well.
I'm using coroutine to delay and reset the flag variable. But you can modify it to your needs.
Additional files: SafeToast.kt
lateinit var toast: Toast
fun Context.safeToast(msg: String, length: Int = Toast.LENGTH_LONG, action: (Context) -> Toast = default) {
toast = SafeToast.makeText(this@safeToast, msg, length).apply {
// do anything new here
action(this@safeToast)
show()
}
}
fun Context.toastSpammable(msg: String) {
cancel()
safeToast(msg, Toast.LENGTH_SHORT)
}
fun Fragment.toastSpammable(msg: String) {
cancel()
requireContext().safeToast(msg, Toast.LENGTH_SHORT)
}
private val default: (Context) -> Toast = { it -> SafeToast.makeText(it, "", Toast.LENGTH_LONG) }
private fun cancel() {
if (::toast.isInitialized) toast.cancel()
}
ActivityUtils.kt
@file:JvmMultifileClass
@file:JvmName("ActivityUtils")
package your.company.com
import android.app.Activity
import your.company.com.R
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
private var backButtonPressedTwice = false
fun Activity.onBackPressedTwiceFinish() {
onBackPressedTwiceFinish(getString(R.string.msg_back_pressed_to_exit), 2000)
}
fun Activity.onBackPressedTwiceFinish(@StringRes message: Int, time: Long) {
onBackPressedTwiceFinish(getString(message), time)
}
fun Activity.onBackPressedTwiceFinish(message: String, time: Long) {
if (backButtonPressedTwice) {
onBackPressed()
} else {
backButtonPressedTwice = true
toastSpammable(message)
GlobalScope.launch {
delay(time)
backButtonPressedTwice = false
}
}
}
Usage in Kotlin
// ActivityA.kt
override fun onBackPressed() {
onBackPressedTwiceFinish()
}
Usage in Java
@Override
public void onBackPressed() {
ActivityUtils.onBackPressedTwiceFinish()
}
This code was inspired by @webserveis here
Do you want the name of the class as a string?
instance.__class__.__name__
xxdiff if you're in Linux land.
To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}
https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes
The \' sequence is invalid.
ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(cPath, "\\", "HHTCtrlp.exe"));
startInfo.Arguments =cParams;
startInfo.UseShellExecute = false;
System.Diagnostics.Process.Start(startInfo);
Data flow diagram: A modeling notation that represents a functional decomposition of a system.
Flow chart: Step by step flow of a programe.
you can also use flask_api for sending response
from flask_api import status
@app.route('/your-api/')
def empty_view(self):
content = {'your content here'}
return content, status.HTTP_201_CREATED
you can find reference here http://www.flaskapi.org/api-guide/status-codes/
I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.
class MathUtil
{
public static boolean betweenExclusive(int x, int min, int max)
{
return x>min && x<max;
}
}
This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..
for jQuery
we can use below:
by input name:
$('input[name="textboxname"]').val('some value');
by input class:
$('input[type=text].textboxclass').val('some value');
by input id:
$('#textboxid').val('some value');
The answer to this requires 3 steps:
argValues
). This is straight forward as it will be available as arguments
inside the function.argNames
). This not as easy and requires parsing the function. Instead of doing the complex regex yourself and worrying about edge cases (default parameters, comments, ...), you can use a library like babylon that will parse the function into an abstract syntax tree from which you can obtain the names of parameters.The code will be like this
const babylon = require("babylon")
function doSomething(a, b, c) {
// get the values of passed argumenst
const argValues = arguments
// get the names of the arguments by parsing the function
const ast = babylon.parse(doSomething.toString())
const argNames = ast.program.body[0].params.map(node => node.name)
// join the 2 arrays, by looping over the longest of 2 arrays
const maxLen = Math.max(argNames.length, argValues.length)
const args = []
for (i = 0; i < maxLen; i++) {
args.push({name: argNames[i], value: argValues[i]})
}
console.log(args)
// implement the actual function here
}
doSomething(1, 2, 3, 4)
and the logged object will be
[
{
"name": "a",
"value": 1
},
{
"name": "c",
"value": 3
},
{
"value": 4
}
]
And here's a working example https://tonicdev.com/5763eb77a945f41300f62a79/5763eb77a945f41300f62a7a
Using javascript seems to be unnecessary if you choose CSS3.
By using :before
selector, you can do this in two lines of CSS. (no script involved).
Another advantage of this approach is that it does not rely on <label>
tag and works even it is missing.
Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).
input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?
You can see a demo here: http://jsfiddle.net/hqZt6/1/
and this one with images:
below will change link and banner every 10 seconds
<script>
var links = ["http://www.abc.com","http://www.def.com","http://www.ghi.com"];
var images = ["http://www.abc.com/1.gif","http://www.def.com/2.gif","http://www.ghi.com/3gif"];
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerLink").href = links[i];
i++;
}
},10000);
</script>
<a id="bannerLink" href="http://www.abc.com" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="http://www.abc.com/1.gif" width="694" height="83" alt="some text">
</a>
If there is no duplicate value in the list:
for i in ints:
indx = ints.index(i)
print(i, indx)
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
I also had to use multiple includes and at 3rd level I needed multiple properties
(from e in context.JobCategorySet
where e.Id == id &&
e.AgencyId == agencyId
select e)
.Include(x => x.JobCategorySkillDetails)
.Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.DurationType))
.Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RuleType))
.Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RateType))
.FirstOrDefaultAsync();
This may help someone :)
Below is my script for converting all files recursively. You can specify folders or files to exclude.
$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"
Function Dos2Unix {
[CmdletBinding()]
Param([Parameter(ValueFromPipeline)] $fileName)
Write-Host -Nonewline "."
$fileContents = Get-Content -raw $fileName
$containsCrLf = $fileContents | %{$_ -match "\r\n"}
If($containsCrLf -contains $true)
{
Write-Host "`r`nCleaing file: $fileName"
set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
}
}
Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }
kk: (01-24) will look like 01, 02..24.
HH:(00-23) will look like 00, 01..23.
hh:(01-12 in AM/PM) will look like 01, 02..12.
so the last printout (working2
) is a bit weird. It should say 12:00:00
(edit: if you were setting the working2
timezone and format, which (as kdagli pointed out) you are not)
Adding on top of majkinetor's answer, here is the way of removing trailing delimiter(since I cannot just comment under his answer yet):
ls -1 | awk 'ORS=","' | head -c -1
Just remove as many trailing bytes as your delimiter counts for.
I like this approach because I can use multi character delimiters + other benefits of awk
:
ls -1 | awk 'ORS=", "' | head -c -2
EDIT
As Peter has noticed, negative byte count is not supported in native MacOS version of head. This however can be easily fixed.
First, install coreutils
. "The GNU Core Utilities are the basic file, shell and text manipulation utilities of the GNU operating system."
brew install coreutils
Commands also provided by MacOS are installed with the prefix "g". For example gls
.
Once you have done this you can use ghead
which has negative byte count, or better, make alias:
alias head="ghead"
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
You can add property to your model as follows:
public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
and then your view will be simpler and will contain no logic at all:
<div class="details @Model.DetailsClass"/>
This will work even with many classes and will not render class if it is null:
<div class="@Model.Class1 @Model.Class2"/>
with 2 not null properties will render:
<div class="class1 class2"/>
if class1 is null
<div class=" class2"/>
Lexeme- A lexeme is a string of character that is the lowest level syntactic unit in the programming language.
Token- The token is a syntactic category that forms a class of lexemes that means which class the lexeme belong is it a keyword or identifier or anything else. One of the major tasks of the lexical analyzer is to create a pair of lexemes and tokens, that is to collect all the characters.
Let us take an example:-
if(y<= t)
y=y-3;
if KEYWORD
( LEFT PARENTHESIS
y IDENTIFIER
< = COMPARISON
t IDENTIFIER
) RIGHT PARENTHESIS
y IDENTIFIER
= ASSGNMENT
y IDENTIFIER
_ ARITHMATIC
3 INTEGER
; SEMICOLON
Relation between Lexeme and Token
Neither main()
or void main()
are standard C. The former is allowed as it has an implicit int
return value, making it the same as int main()
. The purpose of main
's return value is to return an exit status to the operating system.
In standard C, the only valid signatures for main
are:
int main(void)
and
int main(int argc, char **argv)
The form you're using: int main()
is an old style declaration that indicates main
takes an unspecified number of arguments. Don't use it - choose one of those above.
I think it'd be okay if you commented it, e.g. // ^ == XOR
.
The solution I use is.
Using firefox
1. using web developer --> Web Console
2. open the java-script file in new tab.
3. Refresh the new tab you should see your new code.
4. Refresh the original page
5. You should see your changes.
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
I am using this base class connection with mysql:
"base.js"
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 10,
host: Config.appSettings().database.host,
user: Config.appSettings().database.username,
password: Config.appSettings().database.password,
database: Config.appSettings().database.database
});
var DB = (function () {
function _query(query, params, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
callback(null, err);
throw err;
}
connection.query(query, params, function (err, rows) {
connection.release();
if (!err) {
callback(rows);
}
else {
callback(null, err);
}
});
connection.on('error', function (err) {
connection.release();
callback(null, err);
throw err;
});
});
};
return {
query: _query
};
})();
module.exports = DB;
Just use it like that:
var DB = require('../dal/base.js');
DB.query("select * from tasks", null, function (data, error) {
callback(data, error);
});
This is what I preferred from all the recommendations:
Printing from the 6th to last column.
ls -lthr | awk '{out=$6; for(i=7;i<=NF;i++){out=out" "$i}; print out}'
or
ls -lthr | awk '{ORS=" "; for(i=6;i<=NF;i++) print $i;print "\n"}'
Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.
cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));
$.getJSON()
is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON()
. Why not just use $.getJSON()
and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.
It is true, there is currently no $.postJSON()
method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post()
function:
My code looked like this:
$.post('script.php', data, function(response) {
// Do something with the request
}, 'json');
If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@
.
Suppose your commit is in the repo named dev
, and the GitLab issue is in the repo named test
. You can leave a comment on the issue and reference the commit by dev@e9c11f0a
(where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.
Installing psqlODBC on 64bit Windows
Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.
How to configure 32 bit ODBC drivers on Win x64
Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe
%SystemRoot%\syswow64\odbcad32.exe
You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src=">/js/datepicker-fr.js"></script>
<script>
jQuery(function() {
jQuery( "#datepicker" ).datepicker({minDate: 0 , dateFormat: 'mm/dd/yy'});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#datepicker').datepicker($.datepicker.regional['fr']);
});
</script>
This also happens if you forget self
declaration inside class methods.
Example:
class Example():
def is_overlapping(x1, x2, y1, y2):
# Thanks to https://stackoverflow.com/a/12888920/940592
return max(x1, y1) <= min(x2, y2)
Fails calling it like self.is_overlapping(x1=2, x2=4, y1=3, y2=5)
with:
{TypeError} is_overlapping() got multiple values for argument 'x1'
WORKS:
class Example():
def is_overlapping(self, x1, x2, y1, y2):
# Thanks to https://stackoverflow.com/a/12888920/940592
return max(x1, y1) <= min(x2, y2)
In XAMPP Version 1.7.4 server does not have extension=php_openssl.dll line in php ini file. We have to add extension=php_openssl.dll in php.ini file
The Extended WPF Toolkit has one: NumericUpDown
In Python 2:
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
In Python 3:
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.
pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.
awk 'NF' filename
awk 'NF > 0' filename
sed -i '/^$/d' filename
awk '!/^$/' filename
awk '/./' filename
The NF also removes lines containing only blanks or tabs, the regex /^$/
does not.
Map<K,V>
is an interface,
HashMap<K,V>
is a class that implements Map
.
you can do
Map<Key,Value> map = new HashMap<Key,Value>();
Here you have a link to the documentation of each one: Map, HashMap.
IP + "User Agent" could be a better for unique visitor.
if is bootstrap 3 you can use:
$("#mimodal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null);
});
This is due to spring-config.xml is not in classpath.
Add complete path of spring-config.xml to your classpath.
Also write command you execute to run your project. You can check classpath in command.
Always (always, always, I'm not kidding) use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.
http://linuxcommand.org/lc3_man_pages/readh.html
-e use Readline to obtain the line in an interactive shell
Change your read to read -e and annoying line input hang goes away.
In your php.ini file set your extension directory, e.g:
extension_dir = "C:/php/ext/"
You will see in you PHP folder there is an ext folder with all the dll's and extensions.
Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.
Found an XML transform stylesheet here (wayback machine link, site itself is in german)
The stylesheet added here could be helpful:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>", </xsl:if>
<xsl:if test="position() = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.
in C# > 7.0 use
if (obj is null)
...
This will ignore any ==
or !=
defined by the object (unless of course you want to use them ...)
For not null use if (obj is object)
and from C# 9 you can also use if (obj is not null)
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
Download http://www.dll-found.com/download/e/EntityFramework.dll
Paste it in (for x86)
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\
Then Right click on project -> add reference -> select EntityFramework
Bingo......
Add #pragma comment(lib, "Your library name here")
to your source.
For page object model -
@FindBy(xpath="//foo")
public WebElement textBox;
now in your function
public void clearExistingText(String newText){
textBox.clear();
textBox.sendKeys(newText);
}
for general selenium architecture -
driver.findElement(By.xpath("//yourxpath")).clear();
driver.findElement(By.xpath("//yourxpath")).sendKeys("newText");
You can use new Date().getTime()
for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms
into s
.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
You can try PHP protect which is a free PHP obfuscator to obfuscate your PHP code. EDIT: This service is not live anymore.
It is very nice, easy to use and also free.
As for what others have written here about not using obfuscation because it can be broken etc:
I have only one thing to answer them - don't lock your house door because anyone can pick your lock.
This is exactly the case, obfuscation is not meant to prevent 100% code theft. It only needs to make it a time-consuming task so it will be cheaper to pay the original coder. Hope this helps.
Using aLearningLady's answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.
The below code worked for me.
Dim lastrow as Integer
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("C2:C" & lastrow).Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
I faced this problem while running a particular suite of Android for testing on Ubuntu 14.04 (Trusty Tahr). Two things worked for me as suggested by shaheen:
sudo update-ca-certificates -f
sudo /var/lib/dpkg/info/ca-certificates-java.postinst configure
The easiest way to animate Visibility
changes is use Transition API
which available in support (androidx) package. Just call TransitionManager.beginDelayedTransition
method then change visibility of the view. There are several default transitions like Fade
, Slide
.
import androidx.transition.TransitionManager;
import androidx.transition.Transition;
import androidx.transition.Fade;
private void toggle() {
Transition transition = new Fade();
transition.setDuration(600);
transition.addTarget(R.id.image);
TransitionManager.beginDelayedTransition(parent, transition);
image.setVisibility(show ? View.VISIBLE : View.GONE);
}
Where parent
is parent ViewGroup
of animated view. Result:
Here is result with Slide
transition:
import androidx.transition.Slide;
Transition transition = new Slide(Gravity.BOTTOM);
It is easy to write custom transition if you need something different. Here is example with CircularRevealTransition
which I wrote in another answer. It shows and hide view with CircularReveal animation.
Transition transition = new CircularRevealTransition();
android:animateLayoutChanges="true"
option does same thing, it just uses AutoTransition as transition.
Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.
Integer any = new Integer(0);
public synchronized boolean waitTillChange() {
any.wait();
return true;
}
public synchronized void change() {
any.notify();
}
You can bulk import all aliases from one keystore to another:
keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
let a: number[] = [];
a.push(1);
a.push(2);
a.push(3);
let index: number = a.findIndex(a => a === 1);
if (index != -1) {
a.splice(index, 1);
}
console.log(a);
Authentication is done via a simple ldap_bind command that takes the users DN and the password. The user is authenticated when the bind is successfull. Usually you would get the users DN via an ldap_search based on the users uid or email-address.
Getting the users roles is something different as it is an ldap_search and depends on where and how the roles are stored in the ldap. But you might be able to retrieve the roles during the lap_search used to find the users DN.
I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.
Thanks to your answer, I was able to write this little one-liner to improve it. I ran it on my .gitignore and repo, and had no issues, but if anybody sees any glaring problems, please comment. This should git rm -r --cached
from .gitignore
:
cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s/\/$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached
Note that you'll get a lot of fatal: pathspec '<pathspec>' did not match any files
. That's just for the files which haven't been modified.
Intersect the targets with the haystack and make sure the intersection is precisely equal to the targets:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
Note that you only need to verify the size of the resulting intersection is the same size as the array of target values to say that $haystack
is a superset of $target
.
To verify that at least one value in $target
is also in $haystack
, you can do this check:
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}
The non deprecated Objective-C version would be:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://apple.com"] options:@{} completionHandler:nil];
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
Spanish ISO:
Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.
Instead, do:
Get-Date | Select-Object -ExpandProperty DayOfWeek
That will get you the same result as:
(Get-Date).DayOfWeek
The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem)
, for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath
works as expected and returns an array of just the full paths.
I was having the similar issue and solved by understanding the Classes in asp.net C#
I want to read following JSON string :
[
{
"resultList": [
{
"channelType": "",
"duration": "2:29:30",
"episodeno": 0,
"genre": "Drama",
"genreList": [
"Drama"
],
"genres": [
{
"personName": "Drama"
}
],
"id": 1204,
"language": "Hindi",
"name": "The Great Target",
"productId": 1204,
"productMasterId": 1203,
"productMasterName": "The Great Target",
"productName": "The Great Target",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "2005",
"showGoodName": "Movies ",
"views": 8333
},
{
"channelType": "",
"duration": "2:30:30",
"episodeno": 0,
"genre": "Romance",
"genreList": [
"Romance"
],
"genres": [
{
"personName": "Romance"
}
],
"id": 1144,
"language": "Hindi",
"name": "Mere Sapnon Ki Rani",
"productId": 1144,
"productMasterId": 1143,
"productMasterName": "Mere Sapnon Ki Rani",
"productName": "Mere Sapnon Ki Rani",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "1997",
"showGoodName": "Movies ",
"views": 6482
},
{
"channelType": "",
"duration": "2:34:07",
"episodeno": 0,
"genre": "Drama",
"genreList": [
"Drama"
],
"genres": [
{
"personName": "Drama"
}
],
"id": 1520,
"language": "Telugu",
"name": "Satyameva Jayathe",
"productId": 1520,
"productMasterId": 1519,
"productMasterName": "Satyameva Jayathe",
"productName": "Satyameva Jayathe",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "2004",
"showGoodName": "Movies ",
"views": 9910
}
],
"resultSize": 1171,
"pageIndex": "1"
}
]
My asp.net c# code looks like following
First, Class3.cs page created in APP_Code folder of Web application
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;
/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{
public List<ListWrapper_Main> ResultList_Main { get; set; }
public class ListWrapper_Main
{
public List<ListWrapper> ResultList { get; set; }
public string resultSize { get; set; }
public string pageIndex { get; set; }
}
public class ListWrapper
{
public string channelType { get; set; }
public string duration { get; set; }
public int episodeno { get; set; }
public string genre { get; set; }
public string[] genreList { get; set; }
public List<genres_cls> genres { get; set; }
public int id { get; set; }
public string imageUrl { get; set; }
//public string imageurl { get; set; }
public string language { get; set; }
public string name { get; set; }
public int productId { get; set; }
public int productMasterId { get; set; }
public string productMasterName { get; set; }
public string productName { get; set; }
public int productTypeId { get; set; }
public string productTypeName { get; set; }
public decimal rating { get; set; }
public string releaseYear { get; set; }
//public string releaseyear { get; set; }
public string showGoodName { get; set; }
public string views { get; set; }
}
public class genres_cls
{
public string personName { get; set; }
}
}
Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data
JavaScriptSerializer ser = new JavaScriptSerializer();
string final_sb = sb.ToString();
List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());
foreach (var itemdetail in movieInfos)
{
foreach (var itemdetail2 in itemdetail.ResultList)
{
Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
Response.Write("duration=" + itemdetail2.duration + "<br/>");
Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
Response.Write("genre=" + itemdetail2.genre + "<br/>");
string[] genreList_arr = itemdetail2.genreList;
for (int i = 0; i < genreList_arr.Length; i++)
Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");
foreach (var genres1 in itemdetail2.genres)
{
Response.Write("genres1=" + genres1.personName + "<br>");
}
Response.Write("id=" + itemdetail2.id + "<br/>");
Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
//Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
Response.Write("language=" + itemdetail2.language + "<br/>");
Response.Write("name=" + itemdetail2.name + "<br/>");
Response.Write("productId=" + itemdetail2.productId + "<br/>");
Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
Response.Write("productName=" + itemdetail2.productName + "<br/>");
Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
Response.Write("rating=" + itemdetail2.rating + "<br/>");
Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
//Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
Response.Write("views=" + itemdetail2.views + "<br/><br>");
//Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
// Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");
}
Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");
}
'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply
This is basically - web application asp.net c# code....
N joy...
Although similar in general cases ("run and get results for many tasks"), each function has some specific functionality for other cases:
asyncio.gather()
Returns a Future instance, allowing high level grouping of tasks:
import asyncio
from pprint import pprint
import random
async def coro(tag):
print(">", tag)
await asyncio.sleep(random.uniform(1, 3))
print("<", tag)
return tag
loop = asyncio.get_event_loop()
group1 = asyncio.gather(*[coro("group 1.{}".format(i)) for i in range(1, 6)])
group2 = asyncio.gather(*[coro("group 2.{}".format(i)) for i in range(1, 4)])
group3 = asyncio.gather(*[coro("group 3.{}".format(i)) for i in range(1, 10)])
all_groups = asyncio.gather(group1, group2, group3)
results = loop.run_until_complete(all_groups)
loop.close()
pprint(results)
All tasks in a group can be cancelled by calling group2.cancel()
or even all_groups.cancel()
. See also .gather(..., return_exceptions=True)
,
asyncio.wait()
Supports waiting to be stopped after the first task is done, or after a specified timeout, allowing lower level precision of operations:
import asyncio
import random
async def coro(tag):
print(">", tag)
await asyncio.sleep(random.uniform(0.5, 5))
print("<", tag)
return tag
loop = asyncio.get_event_loop()
tasks = [coro(i) for i in range(1, 11)]
print("Get first result:")
finished, unfinished = loop.run_until_complete(
asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED))
for task in finished:
print(task.result())
print("unfinished:", len(unfinished))
print("Get more results in 2 seconds:")
finished2, unfinished2 = loop.run_until_complete(
asyncio.wait(unfinished, timeout=2))
for task in finished2:
print(task.result())
print("unfinished2:", len(unfinished2))
print("Get all other results:")
finished3, unfinished3 = loop.run_until_complete(asyncio.wait(unfinished2))
for task in finished3:
print(task.result())
loop.close()
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.
http://jsfiddle.net/baqxz7ym/2/
document.getElementById("box1").onchange = function(){
if(document.getElementById("box1").value == 1) {
document.getElementById("codigo").setAttribute("readonly", true);
} else {
document.getElementById("codigo").removeAttribute("readonly");
}
};
<input type="text" name="codigo" id="codigo"/>
<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
Go to
C:\ drive
or that drive where xampp is installed
click on xampp
find php and open it , there you find php.ini
folder
open php.ini file with notepad and find upload_max_filesize
and post_max_size
in both "up and down find option",change both values to 1000M
Make your audioSounds
and minTime
variables as static variables, as you are using them in a static method (playSound
).
Marking a method as static
prevents the usage of non-static (instance) members in that method.
To understand more , please read this SO QA:
jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23
link Couting characters, words, lenght of the words and total lenght in a sentence
You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?
Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)
) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...
If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery
instead of getting it from google's CDN.
TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or
document body
) or for some other reason directives like*ngIf
,*ngFor
, custom directives, pipes and other angular utilities like[style.background]
,[class.myOwnCustomClass]
don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example
Try below piece of code.
this.dataGridView1.RefreshEdit();
The above answer is already satisfying the topic. Anyway, if you need all the data in memory - have a look at bcolz. Its compressing the data in memory. I have had really good experience with it. But its missing a lot of pandas features
Edit: I got compression rates at around 1/10 or orig size i think, of course depending of the kind of data. Important features missing were aggregates.
I'd suggest checking for an inner exception. If there isn't one, check your logs for the exception that occurred immediately prior to this one.
This isn't a web-specific exception, I've also encountered it in desktop-app development. In short, what's happening is that the thread receiving this exception is running some asynchronous code (via Invoke(), e.g.) and that code that's being run asynchronously is exploding with an exception. This target invocation exception is the aftermath of that failure.
If you haven't already, place some sort of exception logging wrapper around the asynchronous callbacks that are being invoked when you trigger this error. Event handlers, for instance. That ought to help you track down the problem.
Good luck!
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
There is build in forEach loop for array in ECMAScript 5th Edition.
var buttons = document.getElementsByClassName("navButton");
Array.prototype.forEach.call(buttons,function(button) {
button.setAttribute("class", "active");
button.setAttribute("src", "images/arrows/top_o.png");
});
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
This answer was for @
Neha Gandhi but I modified it for people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer
<html>
<!--Save this as index.php-->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
<?php
// save this as display.php
// show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
//errors ends here
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName = $row['lastName'];
$cell = $row['cell'];
echo "<tr>";
echo "<td align=center>$firstName</td>";
echo "<td align=center>$empid</td>";
echo "<td align=center>$lastName </td>";
echo "<td align=center>$cell</td>";
echo "<td align=center>$cell</td>";
echo "</tr>";
}
echo "</table>";
?>
<?php
// save this as dbconnector.php
function connected_Db(){
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
#echo "Yes we are connected";
return new PDO($dsn,'username','password', $opt);
}
$con = connected_Db();
if($con){
//echo "me is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>
If you want to run several commands in the cmd shell then you can construct a single command like this:
rt.exec("cmd /c start cmd.exe /K \"cd c:/ && dir\"");
This page explains more.
That delay you're talking about is actually a filter to prevent false (unwanted) orientation change notifications.
For instant recognition of device orientation change you're just gonna have to monitor the accelerometer yourself.
Accelerometer measures acceleration (gravity included) in all 3 axes so you shouldn't have any problems in figuring out the actual orientation.
Some code to start working with accelerometer can be found here:
How to make an iPhone App – Part 5: The Accelerometer
And this nice blog covers the math part:
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
Here is Blake's excellent answer as an extension method. Add this to your project and the calls in the question will work as expected.
Meaning it is used like MyNullableDateTime.ToString("dd/MM/yyyy")
, with the same output as MyDateTime.ToString("dd/MM/yyyy")
, except that the value will be "N/A"
if the DateTime is null.
public static string ToString(this DateTime? date, string format)
{
return date != null ? date.Value.ToString(format) : "N/A";
}
PHP by itself has no SMS module or functions and doesn't allow you to send SMS.
SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.
Usually people in telecom business use Asterisk to handle calls and sms programming.
This is really old, but <font size="10">
would be about <p style= "font-size:55px">
System.setProperty("gate.home", "/some/directory");
For more information, see:
System.setProperty( String key , String value )
.The causes of this error are many so first locate your log file and check it for clues. It might be at /usr/local/var/log/postgres.log
or /usr/local/var/postgres/server.log
or possibly elsewhere. If you installed with Homebrew you can find the location in ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
.
// show the marker position //
console.log( objMarker.position.lat() );
console.log( objMarker.position.lng() );
// create a new point based into marker position //
var deltaLat = 1.002;
var deltaLng = -1.003;
var objPoint = new google.maps.LatLng(
parseFloat( objMarker.position.lat() ) + deltaLat,
parseFloat( objMarker.position.lng() ) + deltaLng
);
// now center the map using the new point //
objMap.setCenter( objPoint );
This can be done using the shuffle method:
private List<Integer> getJumbledList() {
List<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(8);
myArrayList2.add(4);
myArrayList2.add(9);
Collections.shuffle(myArrayList2);
return myArrayList2;
Default way to search for recursive file, and available in most cases is
find . -name "filepattern"
It starts recursive traversing for filename or pattern from within current directory where you are positioned. With find command, you can use wildcards, and various switches, to see full list of options, type
man find
or if man pages aren't available at your system
find --help
However, there are more modern and faster tools then find, which are traversing your whole filesystem and indexing your files, one such common tool is locate or slocate/mlocate, you should check manual of your OS on how to install it, and once it's installed it needs to initiate database, if install script don't do it for you, it can be done manually by typing
sudo updatedb
And, to use it to look for some particular file type
locate filename
Or, to look for filename or patter from within current directory, you can type:
pwd | xargs -n 1 -I {} locate "filepattern"
It will look through its database of files and quickly print out path names that match pattern that you have typed.
To see full list of locate's options, type:
locate --help
or man locate
Additionally you can configure locate to update it's database on scheduled times via cron job, so sample cron which updates db at 1AM would look like:
0 1 * * * updatedb
These cron jobs need to be configured by root, since updatedb needs root privilege to traverse whole filesystem.
Take a look at the System
log in Windows EventViewer (eventvwr
from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,
Event Type: Information
Event Source: Service Control Manager
Event Category: None
Event ID: 7036
Date: 7/1/2009
Time: 12:09:43 PM
User: N/A
Computer: MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.
To position an element, a <table>
in your case you want to use either padding or margins.
the difference between margins and paddings can be seen as the "box model":
Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.
I highly recommend the article above if you need to learn how to use CSS.
To move the table down and right I would use margins like so:
table{
margin:25px 0 0 25px;
}
This is in shorthand so the margins are as follows:
margin: top right bottom left;
ax.axis('off')
, will as Joe Kington pointed out, remove everything except the plotted line.
For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the spines
object on the axis. Given an axis object ax
, the following should remove borders on all four sides:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
And, in case of removing x
and y
ticks from the plot:
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
You also can use in this form:
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>
Got it working for a compile file('...')
conflict by increasing minSdkVersion to 21 and enabling multidex. Not sure if that is the best solution but the only way I could get it working in my case.
Note: for compile file('...')
it appears that you cannot put in an exclude
clause so that option was not available.
Given that 'table-layout:fixed' is the essential layout requirement, that this creates evenly spaced non-adjustable columns, but that you need to make cells of different percentage widths, perhaps set the 'colspan' of your cells to a multiple?
For example, using a total width of 100 for easy percentage calculations, and saying that you need one cell of 80% and another of 20%, consider:
<TABLE width=100% style="table-layout:fixed;white-space:nowrap;overflow:hidden;">
<tr>
<td colspan=100>
text across entire width of table
</td>
<tr>
<td colspan=80>
text in lefthand bigger cell
</td>
<td colspan=20>
text in righthand smaller cell
</td>
</TABLE>
Of course, for columns of 80% and 20%, you could just set the 100% width cell colspan to 5, the 80% to 4, and the 20% to 1.
Have a look at the shutil
package, especially rmtree
and copytree
. You can check if a file / path exists with os.paths.exists(<path>)
.
import shutil
import os
def copy_and_overwrite(from_path, to_path):
if os.path.exists(to_path):
shutil.rmtree(to_path)
shutil.copytree(from_path, to_path)
Vincent was right about copytree
not working, if dirs already exist. So distutils
is the nicer version. Below is a fixed version of shutil.copytree
. It's basically copied 1-1, except the first os.makedirs()
put behind an if-else-construct:
import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.isdir(dst): # This one line does the trick
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors
you just need to divide the Date Time stamp by 1000 like:
var a = 1437203995000;
a = (a)/1000;
you can use this after "preventDefault" method
//Here evt.target return default event (eg : defult url etc)
var defaultEvent=evt.target;
//Here we save default event ..
if("true")
{
//activate default event..
location.href(defaultEvent);
}
REVISED - please see Andrew_1510's answer below, as IPython has been updated.
...
It was a bit hard figure out how to get there from a dusty bug report, but:
It ships with IPython now!
import ipy_autoreload
%autoreload 2
%aimport your_mod
# %autoreload? for help
... then every time you call your_mod.dwim()
, it'll pick up the latest version.
Further to Adam Markowitz's answer, here is a general purpose way of (relatively) simply setting the ItemSource
values of a combobox to be enums
, while showing the 'Description' attribute to the user. (You'd think everyone would want to do this so that it would be a .NET one liner, but it just isn't, and this is the most elegant way I've found).
First, create this simple class for converting any Enum value into a ComboBox item:
public class ComboEnumItem {
public string Text { get; set; }
public object Value { get; set; }
public ComboEnumItem(Enum originalEnum)
{
this.Value = originalEnum;
this.Text = this.ToString();
}
public string ToString()
{
FieldInfo field = Value.GetType().GetField(Value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? Value.ToString() : attribute.Description;
}
}
Secondly in your OnLoad
event handler, you need to set the source of your combo box to be a list of ComboEnumItems
based on every Enum
in your Enum
type. This can be achieved with Linq. Then just set the DisplayMemberPath
:
void OnLoad(object sender, RoutedEventArgs e)
{
comboBoxUserReadable.ItemsSource = Enum.GetValues(typeof(EMyEnum))
.Cast<EMyEnum>()
.Select(v => new ComboEnumItem(v))
.ToList();
comboBoxUserReadable.DisplayMemberPath = "Text";
comboBoxUserReadable.SelectedValuePath= "Value";
}
Now the user will select from a list of your user friendly Descriptions
, but what they select will be the enum
value which you can use in code.
To access the user's selection in code, comboBoxUserReadable.SelectedItem
will be the ComboEnumItem
and comboBoxUserReadable.SelectedValue
will be the EMyEnum
.
Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:
def multiple_set_intersection(*sets):
"""Return multiple set intersection."""
try:
return set.intersection(*sets)
except TypeError: # this is Python < 2.6 or no arguments
pass
try: a_set= sets[0]
except IndexError: # no arguments
return set() # return empty set
return reduce(a_set.intersection, sets[1:])
Guido might dislike reduce
, but I'm kind of fond of it :)
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :
, so use
>>> '{0:08b}'.format(1)
'00000001'
You could use the common_schema and use the tokenize
function. For more information about this, follow the links. Your code the would end up like:
call tokenize(name, ' ');
However, be aware that a space is not a reliable separator for first and last name. E.g. In Spain it is common to have two last names.
The newest camera2 apis work fine w/ an emulator that has camera support enabled.
Example for using the newer API:
You will need to use strip()
because of the extra bits in the strings.
A2 = [float(x.strip('"')) for x in A1]
You are looking for a simple code, like this:
List<string> tagList = new List<string>(new[]
{
"A"
,"B"
,"C"
,"D"
,"E"
});
Why not this way:
Public Sub Init(myArguments)
instead of Private Sub Class_Initialize()
Dim myInstance As New myClass: myInstance.Init myArguments
You have to click and hold until the other icon shows up, then slide the mouse down to the icon.
In concurrent and/or asynchronous settings, you may want to verify that certain methods (e.g. delegates, event listeners, response handlers, you name it) are not called. Mocking frameworks aside, you can call fail()
in those methods to fail the tests. Expired timeouts are another natural failure condition in such scenarios.
For example:
final CountDownLatch latch = new CountDownLatch(1);
service.asyncCall(someParameter, new ResponseHandler<SomeType>() {
@Override
public void onSuccess(SomeType result) {
assertNotNull(result);
// Further test assertions on the result
latch.countDown();
}
@Override
public void onError(Exception e) {
fail(exception.getMessage());
latch.countDown();
}
});
if ( !latch.await(5, TimeUnit.SECONDS) ) {
fail("No response after 5s");
}
238! I checked it under Win7 32 bit with the following bat script:
set "fname="
for /l %%i in (1, 1, 27) do @call :setname
@echo %fname%
for /l %%i in (1, 1, 100) do @call :check
goto :EOF
:setname
set "fname=%fname%_123456789"
goto :EOF
:check
set "fname=%fname:~0,-1%"
@echo xx>%fname%
if not exist %fname% goto :eof
dir /b
pause
goto :EOF
Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.
foreach(array_keys($array) as $key) {
// do stuff
}
Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height
in the Navbar section.
Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.
Extended - to provide more details based on some comments
The error
Error TS2306: File 'test.ts' is not a module.
Comes from the fact described here http://exploringjs.com/es6/ch_modules.html
17. Modules
This chapter explains how the built-in modules work in ECMAScript 6.
17.1 OverviewIn ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.
17.1.1 Multiple named exports
There can be multiple named exports:
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } ...
17.1.2 Single default export
There can be a single default export. For example, a function:
//------ myFunc.js ------ export default function () { ··· } // no semicolon!
Based on the above we need the export
, as a part of the test.js file. Let's adjust the content of it like this:
// test.js - exporting es6
export module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
export class OtherClass {
getName(): string {
return 'name';
}
}
}
And now we can import it with these thre ways:
import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";
And we can consume imported stuff like this:
var a1: app1.App.SomeClass = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();
var b1: app2.App.SomeClass = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();
var c1: App.SomeClass = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();
and call the method to see it in action:
console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())
Original part is trying to help to reduce the amount of complexity in usage of the namespace
I would really strongly suggest to check this Q & A:
Let me cite the first sentence:
Do not use "namespaces" in external modules.
Don't do this.
Seriously. Stop.
...
In this case, we just do not need module
inside of test.ts
. This could be the content of it adjusted test.ts
:
export class SomeClass
{
getName(): string
{
return 'name';
}
}
Read more here
In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.
The
export =
syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.
we can later consume it like this:
import App = require('./test');
var sc: App.SomeClass = new App.SomeClass();
sc.getName();
Read more here:
In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.
The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.
The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).
Remember, if you have a string which was read as a line from a text file using the fgets()
function, you need to use substr($string, -3, 1)
so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).
I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.
Testing for name pointing to None
and name existing are two semantically different operations.
To check if val
is None:
if val is None:
pass # val exists and is None
To check if name exists:
try:
val
except NameError:
pass # val does not exist at all
Node is missing from the SYSTEM PATH, try this in your command line
SET PATH=C:\Program Files\Nodejs;%PATH%
and then try running node
To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm
To be very clean, create a new system variable NODEJS
NODEJS="C:\Program Files\Nodejs"
Then edit the PATH
in system variables and add %NODEJS%
PATH=%NODEJS%;...
As to "how do you calculate" Big O, this is part of Computational complexity theory. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.
If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic "worst case" analysis I have found Amortized analysis very useful in practice.
No regex, so no need for //.
this should work:
$str = str_replace("\\", '/', $str);
You need to escape "\" as well.
create PROCEDURE for create custom code using template
create PROCEDURE [dbo].[createCode]
(
@TableName sysname = '',
@befor varchar(max)='public class @TableName
{',
@templet varchar(max)='
public @ColumnType @ColumnName { get; set; } // @ColumnDesc ',
@after varchar(max)='
}'
)
AS
BEGIN
declare @result varchar(max)
set @befor =replace(@befor,'@TableName',@TableName)
set @result=@befor
select @result = @result
+ replace(replace(replace(replace(replace(@templet,'@ColumnType',ColumnType) ,'@ColumnName',ColumnName) ,'@ColumnDesc',ColumnDesc),'@ISPK',ISPK),'@max_length',max_length)
from
(
select
column_id,
replace(col.name, ' ', '_') ColumnName,
typ.name as sqltype,
typ.max_length,
is_identity,
pkk.ISPK,
case typ.name
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'bool'
when 'char' then 'String'
when 'date' then 'DateTime'
when 'datetime' then 'DateTime'
when 'datetime2' then 'DateTime'
when 'datetimeoffset' then 'DateTimeOffset'
when 'decimal' then 'decimal'
when 'float' then 'float'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'decimal'
when 'nchar' then 'char'
when 'ntext' then 'string'
when 'numeric' then 'decimal'
when 'nvarchar' then 'String'
when 'real' then 'double'
when 'smalldatetime' then 'DateTime'
when 'smallint' then 'short'
when 'smallmoney' then 'decimal'
when 'text' then 'String'
when 'time' then 'TimeSpan'
when 'timestamp' then 'DateTime'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'Guid'
when 'varbinary' then 'byte[]'
when 'varchar' then 'string'
else 'UNKNOWN_' + typ.name
END + CASE WHEN col.is_nullable=1 AND typ.name NOT IN ('binary', 'varbinary', 'image', 'text', 'ntext', 'varchar', 'nvarchar', 'char', 'nchar') THEN '?' ELSE '' END ColumnType,
isnull(colDesc.colDesc,'') AS ColumnDesc
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
left join
(
SELECT c.name AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
LEFT JOIN (SELECT K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
ON K.TABLE_NAME = C.TABLE_NAME
AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA
WHERE K.TABLE_NAME = @TableName) as dd
ON dd.COLUMN_NAME = c.name
WHERE t.name = @TableName
) pkk on ColumnName=col.name
OUTER APPLY (
SELECT TOP 1 CAST(value AS NVARCHAR(max)) AS colDesc
FROM
sys.extended_properties
WHERE
major_id = col.object_id
AND
minor_id = COLUMNPROPERTY(major_id, col.name, 'ColumnId')
) colDesc
where object_id = object_id(@TableName)
) t
set @result=@result+@after
select @result
--print @result
END
now create custom code
for example c# class
exec [createCode] @TableName='book',@templet ='
public @ColumnType @ColumnName { get; set; } // @ColumnDesc '
output is
public class book
{
public long ID { get; set; } //
public String Title { get; set; } // Book Title
}
for LINQ
exec [createCode] @TableName='book'
, @befor ='[System.Data.Linq.Mapping.Table(Name = "@TableName")]
public class @TableName
{',
@templet ='
[System.Data.Linq.Mapping.Column(Name = "@ColumnName", IsPrimaryKey = @ISPK)]
public @ColumnType @ColumnName { get; set; } // @ColumnDesc
' ,
@after ='
}'
output is
[System.Data.Linq.Mapping.Table(Name = "book")]
public class book
{
[System.Data.Linq.Mapping.Column(Name = "ID", IsPrimaryKey = true)]
public long ID { get; set; } //
[System.Data.Linq.Mapping.Column(Name = "Title", IsPrimaryKey = false)]
public String Title { get; set; } // Book Title
}
for java class
exec [createCode] @TableName='book',@templet ='
public @ColumnType @ColumnName ; // @ColumnDesc
public @ColumnType get@ColumnName()
{
return this.@ColumnName;
}
public void set@ColumnName(@ColumnType @ColumnName)
{
this.@ColumnName=@ColumnName;
}
'
output is
public class book
{
public long ID ; //
public long getID()
{
return this.ID;
}
public void setID(long ID)
{
this.ID=ID;
}
public String Title ; // Book Title
public String getTitle()
{
return this.Title;
}
public void setTitle(String Title)
{
this.Title=Title;
}
}
for android sugarOrm model
exec [createCode] @TableName='book'
, @befor ='@Table(name = "@TableName")
public class @TableName
{',
@templet ='
@Column(name = "@ColumnName")
public @ColumnType @ColumnName ;// @ColumnDesc
' ,
@after ='
}'
output is
@Table(name = "book")
public class book
{
@Column(name = "ID")
public long ID ;//
@Column(name = "Title")
public String Title ;// Book Title
}
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory,
ApplicationDbContext context)
{
context.Database.Migrate();
...
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
context.getResources().getDisplayMetrics());
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp
llview.addView(tv);
We can do it by using the below code snippet..
Angular Code:
export class AppComponent {
toggleShowHide: string = "visible";
}
HTML Template:
Enter text to hide or show item in bellow:
<input type="text" [(ngModel)]="toggleShowHide">
<br>
Toggle Show/hide:
<div [style.visibility]="toggleShowHide">
Final Release Angular 2!
</div>
From the Rails api on PartialRender:
Rendering the default case
If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.
Examples:
# Instead of <%= render partial: "account" %>
<%= render "account" %>
# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>
# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>
# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>
So, you can use pass a local variable size
to render as follows:
<%= render @users, size: 50 %>
and then use it in the _user.html.erb
partial:
<li>
<%= gravatar_for user, size: size %>
<%= link_to user.name, user %>
</li>
Note that size: size
is equivalent to :size => size
.
Also with dict
a = []
b = {1:'one'}
a.append(dict(b))
print a
b[1]='iuqsdgf'
print a
result
[{1: 'one'}]
[{1: 'one'}]
try this:
mysql -uusername -ppassword --local-infile scrapping -e "LOAD DATA LOCAL INFILE 'CSVname.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
By default, JNDI is disabled in embedded Tomcat which is causing the NoInitialContextException
. You need to call Tomcat.enableNaming()
to enable it. The easiest way to do that is with a TomcatEmbeddedServletContainer
subclass:
@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
@Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
};
}
If you take this approach, you can also register the DataSource
in JNDI by overriding the postProcessContext
method in your TomcatEmbeddedServletContainerFactory
subclass.
context.getNamingResources().addResource
adds the resource to the java:comp/env
context so the resource's name should be jdbc/mydatasource
not java:comp/env/mydatasource
.
Tomcat uses the thread context class loader to determine which JNDI context a lookup should be performed against. You're binding the resource into the web app's JNDI context so you need to ensure that the lookup is performed when the web app's class loader is the thread context class loader. You should be able to achieve this by setting lookupOnStartup
to false
on the jndiObjectFactoryBean
. You'll also need to set expectedType
to javax.sql.DataSource
:
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/mydatasource"/>
<property name="expectedType" value="javax.sql.DataSource"/>
<property name="lookupOnStartup" value="false"/>
</bean>
This will create a proxy for the DataSource with the actual JNDI lookup being performed on first use rather than during application context startup.
The approach described above is illustrated in this Spring Boot sample.
The simplest by far will be Simple http://simple.sourceforge.net, you only need to annotate a single object like so
@Root
public class Entry {
@Attribute
private String a
@Attribute
private int b;
@Element
private Date c;
public String getSomething() {
return a;
}
}
@Root
public class Configuration {
@ElementList(inline=true)
private List<Entry> entries;
public List<Entry> getEntries() {
return entries;
}
}
Then all you have to do to read the whole file is specify the location and it will parse and populate the annotated POJO's. This will do all the type conversions and validation. You can also annotate for persister callbacks if required. Reading it can be done like so.
Serializer serializer = new Persister();
Configuration configuraiton = serializer.read(Configuration.class, fileLocation);
You need to attach the Form1_Load
handler to the Load
event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Height = 100;
mych.Width = 100;
mych.BackColor = SystemColors.Highlight;
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0, 10);
int second = rnd.Next(0, 10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
Controls.Add(mych);
}
}
}
A nice and simple option that worked for me was:
<a href="javascript: false" onClick={this.handlerName}>Click Me</a>
In my case I had a cherry pick that produce a number of Merge Conflicts, so I decide to not complete the cherry pick. I discarded all my changes. Doing so put me into a state where I received the following error:
You have not concluded your merge (MERGE_HEAD exists
To fix the issue I performed the following git command which fixed the problem.
git cherry-pick --abort
FireFox have problemes for getBBox(), i need to do this in vanillaJS.
I've a better Way and is the same result as real svg.getBBox() function !
With this good post : Get the real size of a SVG/G element
var el = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle
console.log( rect.width );
console.log( rect.height);
You want to use coalesce()
:
where coalesce(email, email2) like '%[email protected]%'
If you want to handle empty strings ('') versus NULL, a case works:
where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'
And, if you are worried about the string really being just spaces:
where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'
As an aside, the sample if
statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.
this work for me :D
function setActive() {
aObj = document.getElementById('menu').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
var activeurl = window.location;
$('a[href="'+activeurl+'"]').parent('li').addClass('active');
}
}
}
window.onload = setActive;
If you want to align the div
with pixel accurate, then use float. inline-block
seems to always requires you to chop off a few pixels (at least in IE)
You can't do this with jQuery ajax, but with native XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
EDIT
So revisiting this topic, it seems it is indeed possible to do this with jQuery 3
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.responseType= 'blob'_x000D_
return xhr;_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
or
use xhrFields to set the responseType
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhrFields:{_x000D_
responseType: 'blob'_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
Is there a step missing?
Yes. You need to create the directory:
mkdir ${HOME}/.ssh
Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:
% chmod 700 ~/.ssh
Should the
.ssh
dir be generated when I use thessh-keygen
command?
No. This command generates an SSH key pair but will fail if it cannot write to the required directory:
% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.
Once you've created your keys, you should also restrict who can read those key files to just yourself:
% chmod -R go-wrx ~/.ssh/*
You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.
We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.
On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:
### log just the SQL
log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug
However, the JDBC bind parameters are not being logged.
We can start MySQL service from windows command line using the below command.
net start mysql
Command to stop MySql service:
net stop mysql
Disable MySql service:
sc config mysql start= disabled
Command to enable MySql service(to automatically start MySQL service when the system starts up):
sc config mysql start= auto
Command to set the startup type to manual:
sc config mysql start= manual
How to restart MySql service? There is no direct command to restart a service. You can combine stop and start commands like below.
net stop mysql & net start mysql
Get the hash code of last commit.
git log
git revert <hash_code_from_git_log>
git push
check out in the GHR. you might get what ever you need, hope you this is useful
Warning
create_function()
has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
Builtin loops in PHP are faster then interpreted loops, so it actually makes sense to make this one a one-liner:
$result = array();
array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)
You can add a new property of type IFormFile
to your view model
public class CreatePost
{
public string ImageCaption { set;get; }
public string ImageDescription { set;get; }
public IFormFile MyImage { set; get; }
}
and in your GET action method, we will create an object of this view model and send to the view.
public IActionResult Create()
{
return View(new CreatePost());
}
Now in your Create view which is strongly typed to our view model, have a form
tag which has the enctype
attribute set to "multipart/form-data"
@model CreatePost
<form asp-action="Create" enctype="multipart/form-data">
<input asp-for="ImageCaption"/>
<input asp-for="ImageDescription"/>
<input asp-for="MyImage"/>
<input type="submit"/>
</form>
And your HttpPost action to handle the form posting
[HttpPost]
public IActionResult Create(CreatePost model)
{
var img = model.MyImage;
var imgCaption = model.ImageCaption;
//Getting file meta data
var fileName = Path.GetFileName(model.MyImage.FileName);
var contentType = model.MyImage.ContentType;
// do something with the above data
// to do : return something
}
If you want to upload the file to some directory in your app, you should use IHostingEnvironment
to get the webroot path. Here is a working sample.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public IActionResult Create(CreatePost model)
{
// do other validations on your model as needed
if (model.MyImage != null)
{
var uniqueFileName = GetUniqueFileName(model.MyImage.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads,uniqueFileName);
model.MyImage.CopyTo(new FileStream(filePath, FileMode.Create));
//to do : Save uniqueFileName to your db table
}
// to do : Return something
return RedirectToAction("Index","Home");
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
This will save the file to uploads
folder inside wwwwroot
directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)
Here we are using a very simple GetUniqueName
method which will add 4 chars from a guid to the end of the file name to make it somewhat unique. You can update the method to make it more sophisticated as needed.
Should you be storing the full url to the uploaded image in the database ?
No. Do not store the full url to the image in the database. What if tomorrow your business decides to change your company/product name from www.thefacebook.com
to www.facebook.com
? Now you have to fix all the urls in the table!
What should you store ?
You should store the unique filename which you generated above(the uniqueFileName
varibale we used above) to store the file name. When you want to display the image back, you can use this value (the filename) and build the url to the image.
For example, you can do this in your view.
@{
var imgFileName = "cats_46df.png";
}
<img src="~/uploads/@imgFileName" alt="my img"/>
I just hardcoded an image name to imgFileName
variable and used that. But you may read the stored file name from your database and set to your view model property and use that. Something like
<img src="~/uploads/@Model.FileName" alt="my img"/>
Storing the image to table
If you want to save the file as bytearray/varbinary to your database, you may convert the IFormFile
object to byte array like this
private byte[] GetByteArrayFromImage(IFormFile file)
{
using (var target = new MemoryStream())
{
file.CopyTo(target);
return target.ToArray();
}
}
Now in your http post action method, you can call this method to generate the byte array from IFormFile
and use that to save to your table. the below example is trying to save a Post entity object using entity framework.
[HttpPost]
public IActionResult Create(CreatePost model)
{
//Create an object of your entity class and map property values
var post=new Post() { ImageCaption = model.ImageCaption };
if (model.MyImage != null)
{
post.Image = GetByteArrayFromImage(model.MyImage);
}
_context.Posts.Add(post);
_context.SaveChanges();
return RedirectToAction("Index","Home");
}
If the type implements IDisposable, it automatically disposes that type.
Given:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
These are equivalent:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
The second is easier to read and maintain.
What could be easier than something like this:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
Using tempfile is a lot better than trying to reinvent it.
To check if command line tools are installed run:
xcode-select --version
// if installed you will see the below with the version found in your system
// xcode-select version 1234.
If command line tools are not installed run:
xcode-select --install
You can use == to compare with a zero value composite literal because all fields are comparable:
if (Session{}) == session {
fmt.Println("is zero value")
}
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of ==
above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.
An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
if session.playerId == "" {
fmt.Println("is zero value")
}
If you are using Entity Framework 6, the name space has changed. You want to use
System.Data.Entity.Core.Objects.ObjectQuery
A useful extension is to collect the results in a Dictionary
for fast lookup (e.g. in a loop):
var resultDict = _dbContext.Projects
.Where(p => p.Status == ProjectStatus.Active)
.GroupBy(f => f.Country)
.Select(g => new { country = g.Key, count = g.Count() })
.ToDictionary(k => k.country, i => i.count);
Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c
You can use the below code for it.
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );
Update the create
action as below:
def create
...
respond_to do |format|
if @reservation.save
format.html do
redirect_to '/'
end
format.json { render json: @reservation.to_json }
else
format.html { render 'new'} ## Specify the format in which you are rendering "new" page
format.json { render json: @reservation.errors } ## You might want to specify a json format as well
end
end
end
You are using respond_to
method but anot specifying the format in which a new
page is rendered. Hence, the error ActionController::UnknownFormat
.
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
View.getContext()
: Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext()
: Returns the context for the entire application (the process all the Activities are running inside
of). Use this instead of the current Activity context if you need a
context tied to the lifecycle of the entire application, not just the
current Activity.
ContextWrapper.getBaseContext()
: If you need access to a Context from within another context, you use a ContextWrapper. The
Context referred to from inside that ContextWrapper is accessed via
getBaseContext().
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate
function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.
I recommend using jQuery as it will do all the heavy lifting for you. The code is fairly trivial.
$('input:checkbox').click(function () {
if ($(this).is(':checked')) {
$('#sendNewSms').click(function () {
return false;
});
} else {
$('#sendNewSms').unbind('click');
}
});
The trick is to override the 'click' event and effectively disable it. You can also follow it up with some CSS magic to make it look "disabled". Here is the code in JavaScript in case you need it. It's not perfect but it gets the point across.
var clickEvent = function () {
return false;
};
document.getElementById('#checkbox').onclick(function () {
if (document.getElementById('#checkbox').checked) {
document
.getElementById('#sendNewSms')
.onclick(clickEvent);
} else {
document
.getElementById('#sendNewSms')
.removeEventListener('click', clickEvent, false);
}
});
Try:
import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"
simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon
NB: Based on Paolo's answer.
this works only if WebResponse is a HttpWebResponse.
try
{
...
}
catch (System.Net.WebException exc)
{
var webResponse = exc.Response as System.Net.HttpWebResponse;
if (webResponse != null &&
webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
MessageBox.Show("401");
}
else
throw;
}
You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest
.
package hello.easymock.constructor;
import java.io.File;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
@Test
public void testMockFile() throws Exception {
// first, create a mock for File
final File fileMock = EasyMock.createMock(File.class);
EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
EasyMock.replay(fileMock);
// then return the mocked object if the constructor is invoked
Class<?>[] parameterTypes = new Class[] { String.class };
PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
PowerMock.replay(File.class);
// try constructing a real File and check if the mock kicked in
final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
Assert.assertEquals("/my/fake/file/path", mockedFilePath);
}
}
Pandas Timestamp to datetime.datetime:
pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()
datetime.datetime to Timestamp
pd.Timestamp(datetime(2014, 1, 23))
If you simply want to pass all constructor arguments to the base-class (=parent), here is a minimal example.
This uses templates to forward every constructor call with 1, 2 or 3 arguments to the parent class std::string
.
Code
#include <iostream>
#include <string>
class ChildString: public std::string
{
public:
template<typename... Args>
ChildString(Args... args): std::string(args...)
{
std::cout
<< "\tConstructor call ChildString(nArgs="
<< sizeof...(Args) << "): " << *this
<< std::endl;
}
};
int main()
{
std::cout << "Check out:" << std::endl;
std::cout << "\thttp://www.cplusplus.com/reference/string/string/string/" << std::endl;
std::cout << "for available string constructors" << std::endl;
std::cout << std::endl;
std::cout << "Initialization:" << std::endl;
ChildString cs1 ("copy (2)");
char char_arr[] = "from c-string (4)";
ChildString cs2 (char_arr);
std::string str = "substring (3)";
ChildString cs3 (str, 0, str.length());
std::cout << std::endl;
std::cout << "Usage:" << std::endl;
std::cout << "\tcs1: " << cs1 << std::endl;
std::cout << "\tcs2: " << cs2 << std::endl;
std::cout << "\tcs3: " << cs3 << std::endl;
return 0;
}
Output
Check out:
http://www.cplusplus.com/reference/string/string/string/
for available string constructors
Initialization:
Constructor call ChildString(nArgs=1): copy (2)
Constructor call ChildString(nArgs=1): from c-string (4)
Constructor call ChildString(nArgs=3): substring (3)
Usage:
cs1: copy (2)
cs2: from c-string (4)
cs3: substring (3)
Update: Using Variadic Templates
To generalize to n arguments and simplify
template <class C>
ChildString(C arg): std::string(arg)
{
std::cout << "\tConstructor call ChildString(C arg): " << *this << std::endl;
}
template <class C1, class C2>
ChildString(C1 arg1, C2 arg2): std::string(arg1, arg2)
{
std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
}
template <class C1, class C2, class C3>
ChildString(C1 arg1, C2 arg2, C3 arg3): std::string(arg1, arg2, arg3)
{
std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
}
to
template<typename... Args>
ChildString(Args... args): std::string(args...)
{
std::cout
<< "\tConstructor call ChildString(nArgs="
<< sizeof...(Args) << "): " << *this
<< std::endl;
}
To enable ssh access from the Internet for instances in a VPC subnet do the following:
I solve this issues looking for the name that I passed on my request
I was sending on body:
{thumbbail: <myimg>}
and I was expect to:
upload.single('thumbnail')
so, I fix the name that a send on request
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
setTimeout(function () { location.reload(1); }, 5000);
But as development tools go, you are probably better off with https://addons.mozilla.org/en-US/firefox/addon/115
All you have to do is go to GitHub settings repositories and you see all the sizes right there in the browser no extra work needed.
Create an SSLSocket
factory yourself, and set it on the HttpsURLConnection
before connecting.
...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...
You'll want to create one SSLSocketFactory
and keep it around. Here's a sketch of how to initialize it:
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ...
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();
If you need help creating the key store, please comment.
Here's an example of loading the key store:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();
To create the key store with a PEM format certificate, you can write your own code using CertificateFactory
, or just import it with keytool
from the JDK (keytool won't work for a "key entry", but is just fine for a "trusted entry").
keytool -import -file selfsigned.pem -alias server -keystore server.jks
I was having difficulty getting the answer by @fernando-aguirre using WindowChrome
to work. It was not working in my case because I was overriding OnSourceInitialized
in the MainWindow
and not calling the base class method.
protected override void OnSourceInitialized(EventArgs e)
{
ViewModel.Initialize(this);
base.OnSourceInitialized(e); // <== Need to call this!
}
This stumped me for a very long time.
Best option is to disable sorting and just feed data with desired sort order (from database or other source). Try to add this to your 'datatable': "bSort": false
Return response headers with a reference parameter:
<?php
$data=array('device_token'=>'5641c5b10751c49c07ceb4',
'content'=>'????test'
);
$rtn=curl_to_host('POST', 'http://test.com/send_by_device_token', array(), $data, $resp_headers);
echo $rtn;
var_export($resp_headers);
function curl_to_host($method, $url, $headers, $data, &$resp_headers)
{$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $GLOBALS['POST_TO_HOST.LINE_TIMEOUT']?$GLOBALS['POST_TO_HOST.LINE_TIMEOUT']:5);
curl_setopt($ch, CURLOPT_TIMEOUT, $GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']?$GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']:20);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, 1);
if ($method=='POST')
{curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
foreach ($headers as $k=>$v)
{$headers[$k]=str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $k)))).': '.$v;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$rtn=curl_exec($ch);
curl_close($ch);
$rtn=explode("\r\n\r\nHTTP/", $rtn, 2); //to deal with "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK...\r\n\r\n..." header
$rtn=(count($rtn)>1 ? 'HTTP/' : '').array_pop($rtn);
list($str_resp_headers, $rtn)=explode("\r\n\r\n", $rtn, 2);
$str_resp_headers=explode("\r\n", $str_resp_headers);
array_shift($str_resp_headers); //get rid of "HTTP/1.1 200 OK"
$resp_headers=array();
foreach ($str_resp_headers as $k=>$v)
{$v=explode(': ', $v, 2);
$resp_headers[$v[0]]=$v[1];
}
return $rtn;
}
?>
unanswered core problem persists:
My working directory is now c:\users\projectname.git So then I try to import the project using the eclipse "import" option. When I try to import selecting the option "Use the new projects wizard" the source code is not imported, if I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project. When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?
Yes it should.
It's a bug. Reported here.
Here is a workaround:
Import as general project
Notice the imported data is no valid Eclipse project (no build path available)
Open the .project
xml file in the project folder in Eclipse. If you can't see this file, see How can I get Eclipse to show .* files?.
Go to source
tab
Search for
<natures></natures>
and change it to<natures><nature>org.eclipse.jdt.core.javanature</nature></natures>
and save the file
(idea comes from here)
Right click the src
folder, go to Build Path...
and click Use as Source Folder
After that, you should be able to run & debug the project, and also use team actions via right-click in the package explorer.
If you still have troubles running the project (something like "main class not found"), make sure the <buildSpec>
inside the .project
file is set (as described here):
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
You can't - a set is unordered, so there's no index provided. You'll have to declare an int, as you say. Just remember that the next time you call keySet() you won't necessarily get the results in the same order.
As others already noted, in one case you are attempting to return cString
(which is a char *
value in this context - a pointer) from a function that is declared to return a char
(which is an integer). In another case you do the reverse: you are assigning a char
return value to a char *
pointer. This is what triggers the warnings. You certainly need to declare your return values as char *
, not as char
.
Note BTW that these assignments are in fact constraint violations from the language point of view (i.e. they are "errors"), since it is illegal to mix pointers and integers in C like that (aside from integral constant zero). Your compiler is simply too forgiving in this regard and reports these violations as mere "warnings".
What I also wanted to note is that in several answers you might notice the relatively strange suggestion to return void
from your functions, since you are modifying the string in-place. While it will certainly work (since you indeed are modifying the string in-place), there's nothing really wrong with returning the same value from the function. In fact, it is a rather standard practice in C language where applicable (take a look at the standard functions like strcpy
and others), since it enables "chaining" of function calls if you choose to use it, and costs virtually nothing if you don't use "chaining".
That said, the assignments in your implementation of compareString
look complete superfluous to me (even though they won't break anything). I'd either get rid of them
int compareString(char cString1[], char cString2[]) {
// To lowercase
strToLower(cString1);
strToLower(cString2);
// Do regular strcmp
return strcmp(cString1, cString2);
}
or use "chaining" and do
int compareString(char cString1[], char cString2[]) {
return strcmp(strToLower(cString1), strToLower(cString2));
}
(this is when your char *
return would come handy). Just keep in mind that such "chained" function calls are sometimes difficult to debug with a step-by-step debugger.
As an additional, unrealted note, I'd say that implementing a string comparison function in such a destructive fashion (it modifies the input strings) might not be the best idea. A non-destructive function would be of a much greater value in my opinion. Instead of performing as explicit conversion of the input strings to a lower case, it is usually a better idea to implement a custom char-by-char case-insensitive string comparison function and use it instead of calling the standard strcmp
.
i use below log format for print my content in logCat
Log.e("Msg","What you have to print");
You got the order wrong. The if
should be after the for
(unless it is in an if-else
ternary operator)
[y for y in a if y not in b]
This would work however:
[y if y not in b else other_value for y in a]
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.