Try this:
package my_default;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Get first/desired sheet from the workbook
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
// XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
// because you get Sheet index (1) is out of range (no sheets)
//Write some information in the cells or do what you want
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c2 = row1.createCell(0);
r1c2.setCellValue("NAME");
XSSFCell r1c3 = row1.createCell(1);
r1c3.setCellValue("AGE");
//Save excel to HDD Drive
File pathToFile = new File("D:\\test.xlsx");
if (!pathToFile.exists()) {
pathToFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(pathToFile);
workbook.write(fos);
fos.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}
}
this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.
$query->withCount([
'activity AS paid_sum' => function ($query) {
$query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
}
]);
it returns
"paid_sum_count" => "320.00"
in Deals attribute.
This it now the sum which i wanted to get not the count.
If the schema of id is not of type ObjectId you cannot operate with function : findbyId()
I answered my problem with a default width for all columns and cells, like below:
int width = 15; // Where width is number of caracters
sheet.setDefaultColumnWidth(width);
Using mongoose.js you can count documents,
const count = await Schema.countDocuments();
const count = await Schema.countDocuments({ key: value });
Late answer but you can also try this when defining your schema.
/**
* toJSON implementation
*/
schema.options.toJSON = {
transform: function(doc, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
return ret;
}
};
Note that ret
is the JSON'ed object, and it's not an instance of the mongoose model. You'll operate on it right on object hashes, without getters/setters.
And then:
Model
.findById(modelId)
.exec(function (dbErr, modelDoc){
if(dbErr) return handleErr(dbErr);
return res.send(modelDoc.toJSON(), 200);
});
Edit: Feb 2015
Because I didn't provide a solution to the missing toJSON (or toObject) method(s) I will explain the difference between my usage example and OP's usage example.
OP:
UserModel
.find({}) // will get all users
.exec(function(err, users) {
// supposing that we don't have an error
// and we had users in our collection,
// the users variable here is an array
// of mongoose instances;
// wrong usage (from OP's example)
// return res.end(users.toJSON()); // has no method toJSON
// correct usage
// to apply the toJSON transformation on instances, you have to
// iterate through the users array
var transformedUsers = users.map(function(user) {
return user.toJSON();
});
// finish the request
res.end(transformedUsers);
});
My Example:
UserModel
.findById(someId) // will get a single user
.exec(function(err, user) {
// handle the error, if any
if(err) return handleError(err);
if(null !== user) {
// user might be null if no user matched
// the given id (someId)
// the toJSON method is available here,
// since the user variable here is a
// mongoose model instance
return res.end(user.toJSON());
}
});
SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked . I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies . Full code is given below with exact imports.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFormulaValue {
private static final CellType NUMERIC = null;
public static void main(String[] args) {
try {
readFormula();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
System.out.println("Cell type month is "+cellValue.getCellTypeEnum());
System.out.println("getNumberValue month is "+cellValue.getNumberValue());
// System.out.println("getStringValue "+cellValue.getStringValue());
cellReference = new CellReference("H2"); // pass the cell which contains the formula
row = sheet.getRow(cellReference.getRow());
cell = row.getCell(cellReference.getCol());
cellValue = evaluator.evaluate(cell);
System.out.println("getNumberValue DAY is "+cellValue.getNumberValue());
}
}
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
If you use Maven:
poi => poi-ooxml in artifactId
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
Hera's the function UpdateWindowsList_WindowMenu() that you must call after any operations are performed on Tabs.Here windowToolStripMenuItem is the menu item added to Window Menu to menu strip.
public void UpdateWindowsList_WindowMenu()
{
//get all tab pages from tabControl1
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
//get windowToolStripMenuItem drop down menu items count
int n = windowToolStripMenuItem.DropDownItems.Count;
//remove all menu items from of windowToolStripMenuItem
for (int i = n - 1; i >=2; i--)
{
windowToolStripMenuItem.DropDownItems.RemoveAt(i);
}
//read each tabpage from tabcoll and add each tabpage text to windowToolStripMenuItem
foreach (TabPage tabpage in tabcoll)
{
//create Toolstripmenuitem
ToolStripMenuItem menuitem = new ToolStripMenuItem();
String s = tabpage.Text;
menuitem.Text = s;
if (tabControl1.SelectedTab == tabpage)
{
menuitem.Checked = true;
}
else
{
menuitem.Checked = false;
}
//add menuitem to windowToolStripMenuItem
windowToolStripMenuItem.DropDownItems.Add(menuitem);
//add click events to each added menuitem
menuitem.Click += new System.EventHandler(WindowListEvent_Click);
}
}
private void WindowListEvent_Click(object sender, EventArgs e)
{
//casting ToolStripMenuItem to ToolStripItem
ToolStripItem toolstripitem = (ToolStripItem)sender;
//create collection of tabs of tabContro1
//check every tab text is equal to clicked menuitem then select the tab
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
foreach (TabPage tb in tabcoll)
{
if (toolstripitem.Text == tb.Text)
{
tabControl1.SelectedTab = tb;
//call UpdateWindowsList_WindowMenu() to perform changes on menuitems
UpdateWindowsList_WindowMenu();
}
}
}
or you can write
import.R.layout // at the top
It will work for sure
Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.
Usually I do something like this:
Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.
Also you could use sha1 instead of md5 (or pretty much any algorithm)
%0|%0
is a fork bomb. It will spawn another process using a pipe |
which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).
%0
refers to the command used to run the current program. For example, script.bat
A pipe |
symbol will make the output or result of the first command sequence as the input for the second command sequence. In the case of a fork bomb, there is no output, so it will simply run the second command sequence without any input.
Expanding the example, %0|%0
could mean script.bat|script.bat
. This runs itself again, but also creating another process to run the same program again (with no input).
Here is a way.
We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']
. Then, invoke youtube_dl.main(opts)
. In this way, we write our custom .py module, import youtube_dl
and then invoke the main()
function.
You can use n-number of recipient below method:
String to[] = {"[email protected]"} //Mail id you want to send;
InternetAddress[] address = new InternetAddress[to.length];
for(int i =0; i< to.length; i++)
{
address[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
If have a solution without jQuery. A link where you can see a working example: http://www.letmaier.com/_selectbox/select_general_code.html (styled with more css)
The style-section of my solution:
<style>
#container { margin: 10px; padding: 5px; background: #E7E7E7; width: 300px; background: #ededed); }
#ul1 { display: none; list-style-type: none; list-style-position: outside; margin: 0px; padding: 0px; }
#container a { color: #333333; text-decoration: none; }
#container ul li { padding: 3px; padding-left: 0px; border-bottom: 1px solid #aaa; font-size: 0.8em; cursor: pointer; }
#container ul li:hover { background: #f5f4f4; }
</style>
Now the HTML-code inside the body-tag:
<form>
<div id="container" onMouseOver="document.getElementById('ul1').style.display = 'block';" onMouseOut="document.getElementById('ul1').style.display = 'none';">
Select one entry: <input name="entrytext" type="text" disabled readonly>
<ul id="ul1">
<li onClick="document.forms[0].elements['entrytext'].value='Entry 1'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 1</a></li>
<li onClick="document.forms[0].elements['entrytext'].value='Entry 2'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 2</a></li>
<li onClick="document.forms[0].elements['entrytext'].value='Entry 3'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 3</a></li>
</ul>
</div>
</form>
You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "Press Enter to exit"
Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:
? Open With ? Windows PowerShell
When you right-click a .ps1 file and choose Open With
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
? Run with PowerShell
When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Default Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.
It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:
try
{
# Do your script's stuff
}
catch
{
Write-Error $_.Exception.ToString()
Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
Following worked for me
Enable project-specific settings and set the compliance level to 1.6
How can you do that?
In your Eclipse Package Explorer
3rd click on your project and select properties
. Properties Window will open. Select Java Compiler
on the left panel of the window. Now Enable project specific settings
and set the Complier compliance level
to 1.6
. Select Apply
and then OK
.
Just one other thing to confirm as some people are copy/pasting example code from the Internet to get started. Make sure you have MySQL entered here:
... $dbh = new PDO ("mysql: ...
In some examples this shows
$dbh = new PDO ("dblib ...
Following is one liner for accepted answer ... (for one line lovers ..)
def search_dict(my_dict,searchFor):
s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]
return s_val
You can also convert the URI to file and then to bytes if you want to upload the photo to your server.
Check out : https://www.stackoverflow.com/a/49575321
The poster's second comment from September 21st is spot on. For those who may be coming to this thread later with the same problem as the poster, here is a brief explanation. The other answers are good to keep in mind, but do not address the common issue encountered by this code.
In Swift, declarations made with the let
keyword are constants. Of course if you were going to add items to an array, the array can't be declared as a constant, but a segmented control should be fine, right?! Not if you reference the completed segmented control in its declaration.
Referencing the object (in this case a UISegmentedControl
, but this also happens with UIButton
) in its declaration when you say .addTarget
and let the target be self
, things crash. Why? Because self
is in the midst of being defined. But we do want to define behaviour as part of the object... Declare it lazily as a variable with var
. The lazy
fools the compiler into thinking that self
is well defined - it silences your compiler from caring at the time of declaration. Lazily declared variables don't get set until they are first called. So in this situation, lazy
lets you use the notion of self
without issue while you set up the object, and then when your object gets a .touchUpInside
or .valueChanged
or whatever your 3rd argument is in your .addTarget()
, THEN it calls on the notion of self
, which at that point is fully established and totally prepared to be a valid target. So it lets you be lazy in declaring your variable. In cases like these, I think they could give us a keyword like necessary
, but it is generally seen as a lazy, sloppy practice and you don't want to use it all over your code, though it may have its place in this sort of situation. What it
There is no lazy let
in Swift (no lazy
for constants).
Here is the Apple documentation on lazy.
Here is the Apple on variables and constants. There is a little more in their Language Reference under Declarations.
The Perl documentation comes with a nice collection of FAQs. Your question is frequently asked:
% perldoc -q duplicate
The answer, copy and pasted from the output of the command above, appears below:
Found in /usr/local/lib/perl5/5.10.0/pods/perlfaq4.pod How can I remove duplicate elements from a list or array? (contributed by brian d foy) Use a hash. When you think the words "unique" or "duplicated", think "hash keys". If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use "keys" to get the unique elements. my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array ); my @unique = keys %hash; If you want to use a module, try the "uniq" function from "List::MoreUtils". In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements. use List::MoreUtils qw(uniq); my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7 my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7 You can also go through each element and skip the ones you've seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in %Seen. The "next" statement creates the key and immediately uses its value, which is "undef", so the loop continues to the "push" and increments the value for that key. The next time the loop sees that same element, its key exists in the hash and the value for that key is true (since it's not 0 or "undef"), so the next skips that iteration and the loop goes to the next element. my @unique = (); my %seen = (); foreach my $elem ( @array ) { next if $seen{ $elem }++; push @unique, $elem; } You can write this more briefly using a grep, which does the same thing. my %seen = (); my @unique = grep { ! $seen{ $_ }++ } @array;
You can iterate over the index values if your dataframe has already been created.
df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
print name
print df.loc[name]
The main differenece is that bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.
Note that navigational access is not always good, especially for "one-to-very-many" and "many-to-very-many" relationships. Imagine a Group
that contains thousands of User
s:
How would you access them? With so many User
s, you usually need to apply some filtering and/or pagination, so that you need to execute a query anyway (unless you use collection filtering, which looks like a hack for me). Some developers may tend to apply filtering in memory in such cases, which is obviously not good for performance. Note that having such a relationship can encourage this kind of developers to use it without considering performance implications.
How would you add new User
s to the Group
? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only set User.group
. However, if you want to keep objects in memory consistent, you also need to add User
to Group.users
. But it would make Hibernate to fetch all elements of Group.users
from the database!
So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.
See also:
The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
A(2,3)
ans =
7
A(8)
ans =
7
We can see the order the elements are stored in memory by unrolling the array into a vector.
A(:)
ans =
8
3
4
1
5
9
6
7
2
As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.
find(A>6)
ans =
1
6
8
The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:
B = zeros(size(A));
for i = 1:numel(A)
B(i) = A(i).^2;
end
B
B =
64 1 36
9 25 49
16 81 4
There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.
The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)
You might be better off to use memory-mapped files handling here.. The memory mapped file support will be around in .NET 4 (I think...I heard that through someone else talking about it), hence this wrapper which uses p/invokes to do the same job..
Edit: See here on the MSDN for how it works, here's the blog entry indicating how it is done in the upcoming .NET 4 when it comes out as release. The link I have given earlier on is a wrapper around the pinvoke to achieve this. You can map the entire file into memory, and view it like a sliding window when scrolling through the file.
I've had good success with the asyncproc module, which deals nicely with the output from the processes. For example:
import os
from asynproc import Process
myProc = Process("myprogram.app")
while True:
# check to see if process has ended
poll = myProc.wait(os.WNOHANG)
if poll is not None:
break
# print any new output
out = myProc.read()
if out != "":
print out
Here is a code to split the data into n=5 folds in a stratified manner
% X = data array
% y = Class_label
from sklearn.cross_validation import StratifiedKFold
skf = StratifiedKFold(y, n_folds=5)
for train_index, test_index in skf:
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
There are some predefined formats in date_d.php
to use with format
like:
define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");
Use like this:
$date = new \DateTime();
$string = $date->format(DATE_RFC2822);
In your build.gradle add this dependency:
compile 'com.android.support:multidex:1.0.1'
again in your build.gradle file add this line to defaultConfig block:
multiDexEnabled true
Instead of extending your application class from Application extend it from MultiDexApplication ; like :
public class AppConfig extends MultiDexApplication {
now you're good to go! And in case you need it, all MultiDexApplication
does is
public class MultiDexApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
When installing a tool globally it's to be used by a user as a command line utility anywhere, including outside of node projects. Global installs for a node project are bad because they make deployment more difficult.
The npx
utility bundled with npm
5.2
solves this problem. With it you can invoke locally installed utilities like globally installed utilities (but you must begin the command with npx
). For example, if you want to invoke a locally installed eslint
, you can do:
npx eslint .
When used in a script
field of your package.json, npm
searches node_modules
for the tool as well as globally installed modules, so the local install is sufficient.
So, if you are happy with (in your package.json):
"devDependencies": {
"gulp": "3.5.2"
}
"scripts": {
"test": "gulp test"
}
etc. and running with npm run test
then you shouldn't need the global install at all.
Both methods are useful for getting people set up with your project since sudo
isn't needed. It also means that gulp
will be updated when the version is bumped in the package.json, so everyone will be using the same version of gulp when developing with your project.
It appears that gulp has some unusual behaviour when used globally. When used as a global install, gulp looks for a locally installed gulp to pass control to. Therefore a gulp global install requires a gulp local install to work. The answer above still stands though. Local installs are always preferable to global installs.
Technically, to repair your statement, you can add LIMIT 1
to the subquery to ensure that at most 1 row is returned. That would remove the error, your code would still be nonsense.
... 'SELECT store_key FROM store LIMIT 1' ...
Practically, you want to match rows somehow instead of picking an arbitrary row from the remote table store
to update every row of your local table customer
.
Your rudimentary question doesn't provide enough details, so I am assuming a text column match_name
in both tables (and UNIQUE
in store
) for the sake of this example:
... 'SELECT store_key FROM store
WHERE match_name = ' || quote_literal(customer.match_name) ...
But that's an extremely expensive way of doing things.
Ideally, you should completely rewrite the statement.
UPDATE customer c
SET customer_id = s.store_key
FROM dblink('port=5432, dbname=SERVER1 user=postgres password=309245'
,'SELECT match_name, store_key FROM store')
AS s(match_name text, store_key integer)
WHERE c.match_name = s.match_name
AND c.customer_id IS DISTINCT FROM s.store_key;
This remedies a number of problems in your original statement.
Obviously, the basic problem leading to your error is fixed.
It's almost always better to join in additional relations in the FROM
clause of an UPDATE
statement than to run correlated subqueries for every individual row.
When using dblink, the above becomes a thousand times more important. You do not want to call dblink()
for every single row, that's extremely expensive. Call it once to retrieve all rows you need.
With correlated subqueries, if no row is found in the subquery, the column gets updated to NULL, which is almost always not what you want.
In my updated form, the row only gets updated if a matching row is found. Else, the row is not touched.
Normally, you wouldn't want to update rows, when nothing actually changes. That's expensively doing nothing (but still produces dead rows). The last expression in the WHERE
clause prevents such empty updates:
AND c.customer_id IS DISTINCT FROM sub.store_key
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list
will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.
That said, It's often unavoidable and the functions that do this are:
for 2-D arrays:
for 3-D arrays (the above plus):
for N-D arrays:
The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.
For example,
i >>= 2
produces the same result as
i = i >> 2
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Change the default shell in vs code terminal to git bash.
now your project is open with bash console and right path, put "source venv\Scripts\activate" in Windows
I read through this question, and feel the best way to implement useEffect is not mentioned in the answers. Let's say you have a network call, and would like to do something once you have the response. For the sake of simplicity, let's store the network response in a state variable. One might want to use action/reducer to update the store with the network response.
const [data, setData] = useState(null);
/* This would be called on initial page load */
useEffect(()=>{
fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(data => {
setData(data);
})
.catch(err => {
/* perform error handling if desired */
});
}, [])
/* This would be called when store/state data is updated */
useEffect(()=>{
if (data) {
setPosts(data.children.map(it => {
/* do what you want */
}));
}
}, [data]);
Reference => https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
My Answer: All of the following should be overridden (i.e. describe them all within columndefinition
, if appropriate):
length
precision
scale
nullable
unique
i.e. the column DDL will consist of: name
+ columndefinition
and nothing else.
Rationale follows.
Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.
Other annotation purely logical - properties used in-memory in java to control JPA processing.
That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true)
and once via @Column(...,nullable=true)
. Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.
In your example, length and nullable properties are overridden and redundant.
So, when specifying columnDefinition, what other properties of @Column are made redundant?
In JPA Spec & javadoc:
columnDefinition
definition:
The SQL fragment that is used when generating the DDL for the column.
columnDefinition
default:
Generated SQL to create a column of the inferred type.
The following examples are provided:
@Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
@Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
And, err..., that's it really. :-$ ?!
Does columnDefinition override other properties provided in the same annotation?
The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.
The following can be safely implied from examples provided in the JPA spec
name
& table
can be used in conjunction with columnDefinition
, neither are overriddennullable
is overridden/made redundant by columnDefinition
The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):
length
, precision
, scale
are overridden/made redundant by the columnDefinition
- they are integral to the typeinsertable
and updateable
are provided separately and never included in columnDefinition
, because they control SQL generation in-memory, before it is emmitted to the database.That leaves just the "unique
" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.
Test My Answer For columns "A" & "B", respectively:
@Column(name="...", table="...", insertable=true, updateable=false,
columndefinition="NUMBER(5,2) NOT NULL UNIQUE"
@Column(name="...", table="...", insertable=false, updateable=true,
columndefinition="NVARCHAR2(100) NULL"
I cribbed this and added the 'px'; Works very well.
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: (el.right + window.scrollX ) +'px',
top: (el.top + window.scrollY ) +'px'
}
}
to call: //Gets it to the right side
el.style.top = getOffset(othis).top ;
el.style.left = getOffset(othis).left ;
Yep ! I finally Find it.
implement following code on your button click event, to pop up action sheet as given in the image of question.
UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
theDatePicker.datePickerMode = UIDatePickerModeDate;
theDatePicker.maximumDate=[NSDate date];
}else {
theDatePicker.datePickerMode = UIDatePickerModeTime;
}
self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:doneBtn];
[pickerDateToolbar setItems:barItems animated:YES];
[aac addSubview:pickerDateToolbar];
[aac addSubview:dtpicker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0,0,320, 464)];
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
The other answers are correct but you can omit the [attr.data-index]
altogether and just use
<ul>
<li *ngFor="let item of items; let i = index">{{i + 1}}</li>
</ul
Try this:
>> a = "Smith"
>> a[0]
=> "S"
OR
>> "Smith".chr
#=> "S"
The problem for us was that duplicate submodule entries had been added into .gitmodules (probably from a merge). We searched for the path git complained about in .gitmodules and found the two identical sections. Deleting one of the sections solved the problem for us.
For what it is worth, git 1.7.1 gave the "no submodule mapping" error but git 2.13.0 didn't seem to care.
try this :
if (file_exists(FCPATH . 'uploads/pages/' . $image)) {
unlink(FCPATH . 'uploads/pages/' . $image);
}
My preference is to convert to and from a std::u32string and work with codepoints internally, then convert to utf8 when writing out to a file using these converting iterators I put on github.
#include <utf/utf.h>
int main()
{
using namespace utf;
u32string u32_text = U"?????";
// do stuff with string
// convert to utf8 string
utf32_to_utf8_iterator<u32string::iterator> pos(u32_text.begin());
utf32_to_utf8_iterator<u32string::iterator> end(u32_text.end());
u8string u8_text(pos, end);
// write out utf8 to file.
// ...
}
In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:
https://github.com/romanpitak/PHP-REST-Client
So, getting the xml file:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();
Your problem is with this line:
number4 = list(cow[n])
It tries to take cow[n]
, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Perhaps you meant to put cow[n]
inside a list:
number4 = [cow[n]]
See a demonstration below:
>>> a = 1
>>> [a]
[1]
>>>
Also, I wanted to address two things:
:
at the end.input
like that, since it evaluates its input as real Python code. It would be better here to use raw_input
and then convert the input to an integer with int
.To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum
:
>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
Use a Comparator
like this:
List<Fruit> fruits= new ArrayList<Fruit>();
Fruit fruit;
for(int i = 0; i < 100; i++)
{
fruit = new Fruit();
fruit.setname(...);
fruits.add(fruit);
}
// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
@Override
public int compare(Fruit fruit2, Fruit fruit1)
{
return fruit1.fruitName.compareTo(fruit2.fruitName);
}
});
Now your fruits list is sorted based on fruitName
.
I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]
If you know it's going to be just two fields, you can skip the extra subprocesses like this:
var1=${STR%-*}
var2=${STR#*-}
What does this do? ${STR%-*}
deletes the shortest substring of $STR
that matches the pattern -*
starting from the end of the string. ${STR#*-}
does the same, but with the *-
pattern and starting from the beginning of the string. They each have counterparts %%
and ##
which find the longest anchored pattern match. If anyone has a helpful mnemonic to remember which does which, let me know! I always have to try both to remember.
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
Try running the script explicitly using bash command rather than just executing it as executable.
When it comes to implement a search functionality there are two suggested approach by official Android Developer Documentation.
You can either use a SearchDialog or a SearchWidget.
I am going to explain the implementation of Search functionality using SearchWidget.
I will explain search functionality in a RecyclerView using SearchWidget. It's pretty straightforward.
Just follow these 5 Simple steps
You can add SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
You should initialize SearchView in the onCreateOptionsMenu(Menu menu)
method.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
OnQueryTextListener
has two abstract methods
onQueryTextSubmit(String query)
onQueryTextChange(String newText
So your Activity skeleton would look like this
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
You can provide the implementation for the abstract methods like this
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
Most important part. You can write your own logic to perform search.
Here is mine. This snippet shows the list of Name which contains the text typed in the SearchView
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code on SearchView with an SQLite database in this Music App
You should first take a look at this. This explains what happens when you import a package. For convenience:
The import statement uses the following convention: if a package’s
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported whenfrom package import *
is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package.
So PyCharm respects this by showing a warning message, so that the author can decide which of the modules get imported when * from the package is imported. Thus this seems to be useful feature of PyCharm (and in no way can it be called a bug, I presume). You can easily remove this warning by adding the names of the modules to be imported when your package is imported in the __all__
variable which is list, like this
__init__.py
from . import MyModule1, MyModule2, MyModule3
__all__ = [MyModule1, MyModule2, MyModule3]
After you add this, you can ctrl+click
on these module names used in any other part of your project to directly jump to the declaration, which I often find very useful.
Be sure that you don't use Response
s' methods like Response.Flush();
before your redirecting part.
You should restart your Xampp or whatever server you're runnung, make sure sq
Repeat:
UIImage *img = [UIImage imageNamed:@"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];
Stretched
UIImage *img = [UIImage imageNamed:@"bg.png"];
view.layer.contents = img.CGImage;
public class Test{
static {
loadProperties();
}
static Properties prop;
private static void loadProperties() {
prop = new Properties();
InputStream in = Test.class
.getResourceAsStream("test.properties");
try {
prop.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You can use onLayout
to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:
<View
onLayout={event => {
const layout = event.nativeEvent.layout;
console.log('height:', layout.height);
console.log('width:', layout.width);
console.log('x:', layout.x);
console.log('y:', layout.y);
}}
>
Compared to using .measure()
as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure()
calls with setTimeout
to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.
Your media ID is: 448979387270691659_45818965
This is how to get it.
photo448979387270691659_45818965
There should be your photo ID.
For some reason, this only seems to work with the popup, and not the actual image URL.
ps -Af | grep "tomcat" | grep -v grep | awk '{print$2}' | xargs kill -9
Another way to think about Return-Path
vs Reply-To
is to compare it to snail mail.
When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path
.
Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To
.
In essence, a Postage Return Address is comparable to SMTP's Return-Path
header and SMTP's Reply-To
header is similar to the replying instructions contained in a letter.
Some of my thoughts...
You have to use attachEvent
in IE versions prior to IE9. Detect whether addEventListener
is defined and use attachEvent
if it isn't:
if(_checkbox.addEventListener)
_checkbox.addEventListener("click",setCheckedValues,false);
else
_checkbox.attachEvent("onclick",setCheckedValues);
// ^^ -- onclick, not click
Note that IE11 will remove attachEvent
.
See also:
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
Fastest way to clone an Array of Objects will be using spread operator
var clonedArray=[...originalArray]
but the objects inside that cloned array will still pointing at the old memory location. hence change to clonedArray objects will also change the orignalArray.
var clonedArray = originalArray.map(({...ele}) => {return ele})
this will not only create new array but also the objects will be cloned to.
I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).
After hours of work around most of the solutions here, the problem was solved for me just by installing 32-bit JDK.
I'm assuming you're using jquery to make the AJAX call so you can do this pretty easily by putting the redirect in the success like so:
$.ajax({
url: 'ajax_location.html',
success: function(data) {
//this is the redirect
document.location.href='/newpage/';
}
});
Try, the following code..
@Override
public String toString() {
return this.name();
}
I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.
When using "CreateRepository" there appears to be a difference between .net framework and .net standard.
Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config
GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);
Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config". It wasn't loading the previous known configuration. Once I added the configuration to the configurator it still didn't log, while not complaining about it either.
To get it working under .Net Standard with similar behavior as before, this is what I did.
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");
I didn't want to create a configuration file for every repo, so this works. Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.
Personally I don't find the standard diagramming technique very helpful - the arrows always seem to point the wrong way for me. (They generally point towards the "parent" of each commit, which ends up being backwards in time, which is weird).
To explain it in words:
For reasons I don't understand, GUI tools for Git have never made much of an effort to present merge histories more cleanly, abstracting out the individual merges. So if you want a "clean history", you need to use rebase.
I seem to recall having read blog posts from programmers who only use rebase and others that never use rebase.
I'll try explaining this with a just-words example. Let's say other people on your project are working on the user interface, and you're writing documentation. Without rebase, your history might look something like:
Write tutorial
Merge remote-tracking branch 'origin/master' into fixdocs
Bigger buttons
Drop down list
Extend README
Merge remote-tracking branch 'origin/master' into fixdocs
Make window larger
Fix a mistake in howto.md
That is, merges and UI commits in the middle of your documentation commits.
If you rebased your code onto master instead of merging it, it would look like this:
Write tutorial
Extend README
Fix a mistake in howto.md
Bigger buttons
Drop down list
Make window larger
All of your commits are at the top (newest), followed by the rest of the master
branch.
(Disclaimer: I'm the author of the "10 things I hate about Git" post referred to in another answer)
The following generic solution can be used with regular login, a Spring Social login, or most other Spring Security filters.
In your Spring MVC controller, when loading the product page, save the path to the product page in the session if user has not been logged in. In XML config, set the default target url. For example:
In your Spring MVC controller, the redirect method should read out the path from the session and return redirect:<my_saved_product_path>
.
So, after user logs in, they'll be sent to /redirect
page, which will promptly redirect them back to the product page that they last visited.
Got similar issue. Try to set more time in driver's constructor - add eg.
var timespan = TimeSpan.FromMinutes(3);
var driver = new FirefoxDriver(binary, profile, timeSpan);
.NET Framework 4.6 uses TLS 1.2 by default.
Moreover, only host application should be in .NET 4.6, referenced libraries may remain in older versions.
To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then apply it to your dataframe passing in the axis=1
option:
In [1]: df['C'] = df.apply(f, axis=1)
In [2]: df
Out[2]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.
Edit
Here is the vectorized version
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
Some additions to the shutdown and rundll32.exe shell32.dll,SHExitWindowsEx n
commands.
LOGOFF - allows you to logoff user by sessionid or session name
PSShutdown - requires a download from windows sysinternals.
bootim.exe - windows 10/8 shutdown iu
change/chglogon - prevents new users to login or take another session
NET SESSION /DELETE - ends a session for user
wusa /forcerestart /quiet - windows update manager but also can restart the machine
tsdiscon - disconnects you
rdpinit - logs you out , though I cant find any documentation at the moment
Like the others said, you probably missunderstood the idea of a unique id. All I have to add is, that I do not like the idea of using "value" as the identifying property here, as it may change over time (i.e. if you want to provide multiple languages).
<input id='submit_tea' type='submit' name = 'submit_tea' value = 'Tea' />
<input id='submit_coffee' type='submit' name = 'submit_coffee' value = 'Coffee' />
and in your php script
if( array_key_exists( 'submit_tea', $_POST ) )
{
// handle tea
}
if( array_key_exists( 'submit_coffee', $_POST ) )
{
// handle coffee
}
Additionally, you can add something like if( 'POST' == $_SERVER[ 'REQUEST_METHOD' ] )
if you want to check if data was acctually posted.
In PHP you need fist to define the variable after that you can use it.
We can check variable is defined or not in very efficient way!.
//If you only want to check variable has value and value has true and false value.
//But variable must be defined first.
if($my_variable_name){
}
//If you want to check variable is define or undefine
//Isset() does not check that variable has true or false value
//But it check null value of variable
if(isset($my_variable_name)){
}
Simple Explanation
//It will work with :- true,false,NULL
$defineVarialbe = false;
if($defineVarialbe){
echo "true";
}else{
echo "false";
}
//It will check variable is define or not and variable has null value.
if(isset($unDefineVarialbe)){
echo "true";
}else{
echo "false";
}
Using dplyr:
library(dplyr)
# exclude ID column then get mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., -ID)))
Or
# select the columns to include in mean
DF %>%
transmute(ID,
Mean = rowMeans(select(., C1:C3)))
# ID Mean
# 1 A 3.666667
# 2 B 4.333333
# 3 C 3.333333
# 4 D 4.666667
# 5 E 4.333333
From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
So in your case, when: deployed_revision is not defined
should work
$.ajax({
type: "POST",
data: {data:the_id},
url: "http://localhost/test/index.php/data/count_votes",
success: function(data){
//data will contain the vote count echoed by the controller i.e.
"yourVoteCount"
//then append the result where ever you want like
$("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller
}
});
in the controller
$data = $_POST['data']; //$data will contain the_id
//do some processing
echo "yourVoteCount";
Clarification
i think you are confusing
{data:the_id}
with
success:function(data){
both the data
are different for your own clarity sake you can modify it as
success:function(vote_count){
$(span#someId).html(vote_count);
The binary operators =
(assignment), []
(array subscription), ->
(member access), as well as the n-ary ()
(function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.
Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators <<
and >>
, whose left operands are stream classes from the standard library which you cannot change.
For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:
Of course, as with all rules of thumb, there are exceptions. If you have a type
enum Month {Jan, Feb, ..., Nov, Dec}
and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<()
for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.
(However, if you make an exception, do not forget the issue of const
-ness for the operand that, for member functions, becomes the implicit this
argument. If the operator as a non-member function would take its left-most argument as a const
reference, the same operator as a member function needs to have a const
at the end to make *this
a const
reference.)
Continue to Common operators to overload.
Alex Answer is pretty neat but when using context rotate it can be hard to trace x,y coordinates, so I have made a Demo showing how to keep track of that.
Basically I am using this function & giving it the angle & the amount of distance traveled in that angel before drawing object.
function rotCor(angle, length){
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newx = length*cos;
var newy = length*sin;
return {
x : newx,
y : newy
};
}
You can use Thread.currentThread().getStackTrace()
.
That returns an array of StackTraceElement
s that represent the current stack trace of a program.
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
If you have tried everything regarding this issue to no avail, you'll end up where I did. It turns out, Amazon's existing CORS setup directions work just fine... just make sure you remember to redeploy! The CORS editing wizard, even with all its nice little green checkmarks, does not make live updates to your API. Perhaps obvious, but it stumped me for half a day.
Heres a truly "Reversible Dictionary", Based upon Adam Acosta's solution, but enforcing val-to-key calls to be unique and easily return key from value:
from collections import UserDict
class ReversibleDict(UserDict):
def __init__(self, enforce_unique=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.val_to_keys = {}
self.check_val = self.check_unique if enforce_unique else lambda x: x
def __setitem__(self, key, value):
self.check_val(value)
super().__setitem__(key, value)
self.val_to_keys[value] = key
def __call__(self, value):
return self.val_to_keys[value]
def check_unique(self, value):
assert value not in self.val_to_keys, f"Non unique value '{value}'"
return value
If you want to enforce uniqueness on dictionary values ensure to set enforce_unique=True. to get keys from values just do rev_dict(value), to call values from keys just do as usual dict['key'], here's an example of usage:
rev_dict = ReversibleDict(enforce_unique=True)
rev_dict["a"] = 1
rev_dict["b"] = 2
rev_dict["c"] = 3
print("full dictinoary is: ", rev_dict)
print("value for key 'b' is: ", rev_dict["b"])
print("key for value '2' is: ", rev_dict(2))
print("tring to set another key with the same value results in error: ")
rev_dict["d"] = 1
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!
Depending on the level of precision you require you can work it out yourself, using the simple proof of differentiation:
>>> (((5 + 0.1) ** 2 + 1) - ((5) ** 2 + 1)) / 0.1
10.09999999999998
>>> (((5 + 0.01) ** 2 + 1) - ((5) ** 2 + 1)) / 0.01
10.009999999999764
>>> (((5 + 0.0000000001) ** 2 + 1) - ((5) ** 2 + 1)) / 0.0000000001
10.00000082740371
we can't actually take the limit of the gradient, but its kinda fun. You gotta watch out though because
>>> (((5+0.0000000000000001)**2+1)-((5)**2+1))/0.0000000000000001
0.0
Class Row
will handle one row from your database.
Complete implementation of UpdateTask responsible for filling up UI.
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.SwingWorker;
public class JTableUpdateTask extends SwingWorker<JTable, Row> {
JTable table = null;
ResultSet resultSet = null;
public JTableUpdateTask(JTable table, ResultSet rs) {
this.table = table;
this.resultSet = rs;
}
@Override
protected JTable doInBackground() throws Exception {
List<Row> rows = new ArrayList<Row>();
Object[] values = new Object[6];
while (resultSet.next()) {
values = new Object[6];
values[0] = resultSet.getString("id");
values[1] = resultSet.getString("student_name");
values[2] = resultSet.getString("street");
values[3] = resultSet.getString("city");
values[4] = resultSet.getString("state");
values[5] = resultSet.getString("zipcode");
Row row = new Row(values);
rows.add(row);
}
process(rows);
return this.table;
}
protected void process(List<Row> chunks) {
ResultSetTableModel tableModel = (this.table.getModel() instanceof ResultSetTableModel ? (ResultSetTableModel) this.table.getModel() : null);
if (tableModel == null) {
try {
tableModel = new ResultSetTableModel(this.resultSet.getMetaData(), chunks);
} catch (SQLException e) {
e.printStackTrace();
}
this.table.setModel(tableModel);
} else {
tableModel.getRows().addAll(chunks);
}
tableModel.fireTableDataChanged();
}
}
Table Model:
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
* Simple wrapper around Object[] representing a row from the ResultSet.
*/
class Row {
private final Object[] values;
public Row(Object[] values) {
this.values = values;
}
public int getSize() {
return values.length;
}
public Object getValue(int i) {
return values[i];
}
}
// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
private final ResultSetMetaData rsmd;
private List<Row> rows;
public ResultSetTableModel(ResultSetMetaData rsmd, List<Row> rows) {
this.rsmd = rsmd;
if (rows != null) {
this.rows = rows;
} else {
this.rows = new ArrayList<Row>();
}
}
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
try {
return rsmd.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public Object getValue(int row, int column) {
return rows.get(row).getValue(column);
}
public String getColumnName(int col) {
try {
return rsmd.getColumnName(col + 1);
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
public Class<?> getColumnClass(int col) {
String className = "";
try {
className = rsmd.getColumnClassName(col);
} catch (SQLException e) {
e.printStackTrace();
}
return className.getClass();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(rowIndex > rows.size()){
return null;
}
return rows.get(rowIndex).getValue(columnIndex);
}
public List<Row> getRows() {
return this.rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
}
Main Application which builds UI and does the database connection
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
public class MainApp {
static Connection conn = null;
static void init(final ResultSet rs) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTable table = new JTable();
table.setPreferredSize(new Dimension(300,300));
table.setMinimumSize(new Dimension(300,300));
table.setMaximumSize(new Dimension(300,300));
frame.add(table, BorderLayout.CENTER);
JButton button = new JButton("Start Loading");
button.setPreferredSize(new Dimension(30,30));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JTableUpdateTask jTableUpdateTask = new JTableUpdateTask(table, rs);
jTableUpdateTask.execute();
}
});
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
PreparedStatement pstmt = conn.prepareStatement("Select id, student_name, street, city, state,zipcode from student");
ResultSet rs = pstmt.executeQuery();
init(rs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have changed to your code with little modification will works well. Here is the code:
butangDonload.php
<?php
$file = "logo_ldg.png"; //Let say If I put the file name Bang.png
echo "<a href='download1.php?nama=".$file."'>download</a> ";
?>
download.php
<?php
$name= $_GET['nama'];
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
ob_clean();
flush();
readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
exit;
?>
Here you need to show the path from where the file to be download. i.e. will just give the file name but need to give the file path for reading that file. So, it should be replaced by I have tested by using your code and modifying also will works.
Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.
In the case of the first block:
filecontent()
{
setGUI();
setRegister();
showfile();
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
You would have to include a try catch block:
filecontent()
{
setGUI();
setRegister();
try {
showfile();
}
catch (IOException e) {
// Do something here
}
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
In the case of the second:
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == submit)
{
showfile();
}
}
You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try {
showfile();
}
catch (IOException e) {
// Do something here
}
}
}
Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.
If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.
Inline:
<select
onchange="var val = this.options[this.selectedIndex].value;
this.form.color[1].style.display=(val=='others')?'block':'none'">
I used to do this
In the head (give the select an ID):
window.onload=function() {
var sel = document.getElementById('color');
sel.onchange=function() {
var val = this.options[this.selectedIndex].value;
if (val == 'others') {
var newOption = prompt('Your own color','');
if (newOption) {
this.options[this.options.length-1].text = newOption;
this.options[this.options.length-1].value = newOption;
this.options[this.options.length] = new Option('other','other');
}
}
}
}
If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works.
The find
command can output many parameters.
For example, add the following to the --printf
clause:
%a for attributes in the octal format
%n for the file name including a complete path
Example:
find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file
Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.
Spent much of my time with this! My bad! Later found that the class on which I declared the annotation Service
or Component
was of type abstract. Had enabled debug logs on Springframework but no hint was received. Please check if the class if of abstract type. If then, the basic rule applied, can't instantiate an abstract class.
my solution is
navigationText: ["", ""]
full code is below:
var owl1 = $("#main-demo");
owl1.owlCarousel({
navigation: true, // Show next and prev buttons
slideSpeed: 300,
pagination:false,
singleItem: true, transitionStyle: "fade",
navigationText: ["", ""]
});// Custom Navigation Events
owl1.trigger('owl.play', 4500);
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
... right now it happens only to the website I'm testing. I can't post it here because it's confidential.
Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use
--secure-protocol=TLSv1
. If this does not help check if you can access the site with openssl s_client -connect ...
(probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ...
.
Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.
The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.
Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?
The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.
This is a one-liner alternative to Mike Q's function:
secs_to_human() {
echo "$(( ${1} / 3600 ))h $(( (${1} / 60) % 60 ))m $(( ${1} % 60 ))s"
}
in /usr/bin
type
sudo ln -s -f g++-4.2 g++
sudo ln -s -f gcc-4.2 gcc
That should do it.
Here is the other way to get scroll position
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
just found
grep $'\r'
It's using $'\r'
for c-style escape in Bash.
in this article
If you are familiar with git you'll be happy to use histedit that works like git rebase -i
.
The above answer is great or if it will not hurt you, just rollback the migration and change the name and run migration again.
php artisan migrate:rollback
In Visual Studio 2013 I struggled with this for a while and it is pretty much easy to solve just follow what the exceptions says "virtual directory not being configured as an application in IIS"
In my case I had WebService
planted inside IIS website
so
Convert to Application
Ok
WCF is back and running.
Although you could certainly use the compareTo
method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.
Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:
if (count > 0) { }
And the Integer
instance count
gets automatically converted to an int
for the comparison.
If you're having trouble understanding this, check out the link above, or imagine it's doing this:
if (count.intValue() > 0) { }
The instanceof-operator is called is
in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.
Here's an example:
class Foo { }
main() {
var foo = new Foo();
if (foo is Foo) {
print("it's a foo!");
}
}
I like ZenBurn theme, I think it is very mild and appealing for the eye. I had here my own theme's settings JAR file, but I stopped updating it. I still think that theme is very good so I updated this post to a suitable theme with similar colors which is already available on @Yarg's web site
The various answers in this blog seem to be defined by SE's who promote strict adherence to the usual rules of object-oriented programming (use a Public Class with public shared (aka static), and fully-qualified class references, or SE's who promote using the backward-compatibility feature (Module) for which the compiler obviously needs to do the same thing to make it work.
As a SE with 30+ years of experience, I would propose the following guidelines:
If you are writing all new code (not attempting to convert a legacy app) that you avoid using these forms altogether except in the rare instance that you really DO need to have a static variable because they can cause terrible consequences (and really hard-to-find bugs). (Multithread and multiprocessing code requires semaphores around static variables...)
If you are modifying a small application that already has a few global variables, then formulate them so they are not obscured by Modules, that is, use the standard rules of object-oriented programming to re-create them as public static and access them by full qualification so others can figure out what is going on.
If you have a huge legacy application with dozens or hundreds of global variables, by all means, use Modules to define them. There is no reason to waste time when getting the application working, because you are probably already behind the 8-ball in time spent on Properties, etc.
From a quick glance on MDN I think you may need to include the .js
at the end of your file name so the import would read
import './course.js'
instead of import './course'
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Doing some piggybacking off existing answers here:
public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
return new DateTime().Add(timeSpan).ToShortTimeString();
}
public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}
You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.
Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.
First all need to do is start hadoop nodes and Trackers, simply by typing start-all.sh on ur terminal. To check all the trackers and nodes are started write 'jps' command. if everything is fine and working, go to your browser type the following url http://localhost:50070
Just use the below code to resolve this:
JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
replace('-', '+').replace('_', '/')))).readObject();
In the above code replace('-', '+').replace('_', '/')
did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
I faced the same issue. In my case, part of my variables were in a dictionary i.e. with_dict variable (looping) and I had to run 3 commands on each item.key. This solution is more relevant where you have to use with_dict dictionary with running multiple commands (without requiring with_items)
Using with_dict and with_items in one task didn't help as it was not resolving the variables.
My task was like:
- name: Make install git source
command: "{{ item }}"
with_items:
- cd {{ tools_dir }}/{{ item.value.artifact_dir }}
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} all
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} install
with_dict: "{{ git_versions }}"
roles/git/defaults/main.yml was:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
The above resulted in an error similar to the following for each {{ item }} (for 3 commands as mentioned above). As you see, the values of tools_dir is not populated (tools_dir is a variable which is defined in a common role's defaults/main.yml and also item.value.git_tar_dir value was not populated/resolved).
failed: [server01.poc.jenkins] => (item=cd {# tools_dir #}/{# item.value.git_tar_dir #}) => {"cmd": "cd '{#' tools_dir '#}/{#' item.value.git_tar_dir '#}'", "failed": true, "item": "cd {# tools_dir #}/{# item.value.git_tar_dir #}", "rc": 2}
msg: [Errno 2] No such file or directory
Solution was easy. Instead of using "COMMAND" module in Ansible, I used "Shell" module and created a a variable in roles/git/defaults/main.yml
So, now roles/git/defaults/main.yml looks like:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} all && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} install"
#or use this if you want git installation to work in ~/tools/git-x.x.x
git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix=`pwd` all && make prefix=`pwd` install"
#or use this if you want git installation to use the default prefix during make
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make all && make install"
and the task roles/git/tasks/main.yml looks like:
- name: Make install from git source
shell: "{{ git_pre_requisites_install_cmds }}"
become_user: "{{ build_user }}"
with_dict: "{{ git_versions }}"
tags:
- koba
This time, the values got successfully substituted as the module was "SHELL" and ansible output echoed the correct values. This didn't require with_items: loop.
"cmd": "cd ~/tools/git-2.6.3 && make prefix=/home/giga/tools/git-2.6.3 all && make prefix=/home/giga/tools/git-2.6.3 install",
I use Hibernate 5.2 and @Temporal
is not required anymore.
java.util.date, sql.date, time.LocalDate are stored into DB with appropriate datatype as Date/timestamp.
I take the below approach to remove the item in slice. This helps in readability for others. And also immutable.
func remove(items []string, item string) []string {
newitems := []string{}
for _, i := range items {
if i != item {
newitems = append(newitems, i)
}
}
return newitems
}
As a workaround a generic "ObjectHolder" can be used. See code example below.
The sample output is:
name: John Doe
dob:1953-12-17
name: Jim Miller
dob:1947-04-18
so the Person parameter has been modified since it's wrapped in the Holder which is passed by value - the generic param inside is a reference where the contents can be modified - so actually a different person is returned and the original stays as is.
/**
* show work around for missing call by reference in java
*/
public class OutparamTest {
/**
* a test class to be used as parameter
*/
public static class Person {
public String name;
public String dob;
public void show() {
System.out.println("name: "+name+"\ndob:"+dob);
}
}
/**
* ObjectHolder (Generic ParameterWrapper)
*/
public static class ObjectHolder<T> {
public ObjectHolder(T param) {
this.param=param;
}
public T param;
}
/**
* ObjectHolder is substitute for missing "out" parameter
*/
public static void setPersonData(ObjectHolder<Person> personHolder,String name,String dob) {
// Holder needs to be dereferenced to get access to content
personHolder.param=new Person();
personHolder.param.name=name;
personHolder.param.dob=dob;
}
/**
* show how it works
*/
public static void main(String args[]) {
Person jim=new Person();
jim.name="Jim Miller";
jim.dob="1947-04-18";
ObjectHolder<Person> testPersonHolder=new ObjectHolder(jim);
// modify the testPersonHolder person content by actually creating and returning
// a new Person in the "out parameter"
setPersonData(testPersonHolder,"John Doe","1953-12-17");
testPersonHolder.param.show();
jim.show();
}
}
SELECT session_id as SPID, command, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time, a.text AS Query FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a WHERE r.command in ('BACKUP DATABASE', 'BACKUP LOG', 'RESTORE DATABASE', 'RESTORE LOG')
I've been using this guy to do the job: https://github.com/weichx/cerialize
It's very simple yet powerful. It supports:
Example:
class Tree {
@deserialize public species : string;
@deserializeAs(Leaf) public leafs : Array<Leaf>; //arrays do not need extra specifications, just a type.
@deserializeAs(Bark, 'barkType') public bark : Bark; //using custom type and custom key name
@deserializeIndexable(Leaf) public leafMap : {[idx : string] : Leaf}; //use an object as a map
}
class Leaf {
@deserialize public color : string;
@deserialize public blooming : boolean;
@deserializeAs(Date) public bloomedAt : Date;
}
class Bark {
@deserialize roughness : number;
}
var json = {
species: 'Oak',
barkType: { roughness: 1 },
leafs: [ {color: 'red', blooming: false, bloomedAt: 'Mon Dec 07 2015 11:48:20 GMT-0500 (EST)' } ],
leafMap: { type1: { some leaf data }, type2: { some leaf data } }
}
var tree: Tree = Deserialize(json, Tree);
I ran into this issue with Python 3.6
and Python 3.7
. The top answer (running pip install --upgrade pip enum34
) did not solve the problem.
I don't know why, but the reason why this error happen is because enum.py
was missing from .venv/myvenv/lib/python3.7/
.
But the file was in /usr/lib/python3.7/
.
Following this answer, I just created the symbolic link by myself :
ln -s /usr/lib/python3.7/enum.py .venv/myvenv/lib/python3.7/enum.py
Apart from having a Path
variable, the directory C:\data\db
is mandatory.
Create this and the error shall be solved.
This error comes when there is error in your query syntax check field names table name, mean check your query syntax.
If one of the tables M
, S
, D
, or H
has more than one row for a given Id
(if just the Id
column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id
in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).
References:
Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
I have recently done something similar to this using the "Haversine Formula" on WGS-84 data, which is a derivative of the "Law of Haversines" with very satisfying results.
Yes, WGS-84 assumes the Earth is an ellipsoid, but I believe you only get about a 0.5% average error using an approach like the "Haversine Formula", which may be an acceptable amount of error in your case. You will always have some amount of error unless you're talking about a distance of a few feet and even then there is theoretically curvature of the Earth... If you require a more rigidly WGS-84 compatible approach checkout the "Vincenty Formula."
I understand where starblue is coming from, but good software engineering is often about trade-offs, so it all depends on the accuracy you require for what you are doing. For example, the result calculated from "Manhattan Distance Formula" versus the result from the "Distance Formula" can be better for certain situations as it is computationally less expensive. Think "which point is closest?" scenarios where you don't need a precise distance measurement.
Regarding, the "Haversine Formula" it is easy to implement and is nice because it is using "Spherical Trigonometry" instead of a "Law of Cosines" based approach which is based on two-dimensional trigonometry, therefore you get a nice balance of accuracy over complexity.
A gentleman by the name of Chris Veness has a great website that explains some of the concepts you are interested in and demonstrates various programmatic implementations; this should answer your x/y conversion question as well.
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/>
in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Going by the Mathematical Definition of Floor, that is, "Greatest integer less than or equal to a number", This is completely unambiguous, whereas, Truncate just removes the fractional part, which is equivalent to round towards 0.
You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:
SELECT Name,
SUM(Value) AS "SUM(VALUE)",
SUM(Value) / totals.total AS "% of Total"
FROM table1,
(
SELECT Name,
SUM(Value) AS total
FROM table1
GROUP BY Name
) AS totals
WHERE table1.Name = totals.Name
AND Year BETWEEN 2000 AND 2001
GROUP BY Name;
Note that the subquery does not have the WHERE clause filtering the years.
Just right click on the Visual Studio icon and then select "New Window" from the contextual toolbar that appears on the bottom in Windows 8. A new instance of Visual Studio will launch and then you can open your second project.
Your best bet is to look up php_gd2. It's a fairly decent image library that comes with PHP (just disabled in php.ini), and not only can you output your finished images in a couple formats, it's got enough functions that you should be able to do up a good graph fairly easily.
EDIT: it might help if I gave you a couple useful links:
http://www.libgd.org/ - You can get the latest php_gd2
here
http://ca3.php.net/gd - The php_gd
manual.
Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:
This is how I always do maths in Bash:
count=$(echo "$FIRSTV - $SECONDV"|bc)
echo $count
Here's a solution I used (it needs #include <time.h>
):
int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();
do {
/*
* Do something to busy the CPU just here while you drink a coffee
* Be sure this code will not take more than `trigger` ms
*/
clock_t difference = clock() - before;
msec = difference * 1000 / CLOCKS_PER_SEC;
iterations++;
} while ( msec < trigger );
printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
msec/1000, msec%1000, iterations);
It is just to initialize the instance's variables.
E.g. create a crawler
instance with a specific database name (from your example above).
You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.
In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.
Use this in your code:
String.valueOf(x);
For short month names use:
string monthName = new DateTime(2010, 8, 1)
.ToString("MMM", CultureInfo.InvariantCulture);
For long/full month names for Spanish ("es") culture
string fullMonthName = new DateTime(2015, i, 1).ToString("MMMM", CultureInfo.CreateSpecificCulture("es"));
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use
process.env[v]
.
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
If you want to create a new input field with for example file
type:
// Create a new Input with type file and id='file-input'
var newFileInput = document.createElement('input');
// The new input file will have type 'file'
newFileInput.type = "file";
// The new input file will have class="w-95 mb-1" (width - 95%, margin-bottom: .25rem)
newFileInput.className = "w-95 mb-1"
The output will be: <input type="file" class="w-95 mb-1">
If you want to create a nested tag using JavaScript, the simplest way is with innerHtml
:
var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';
The output will be:
<li>
<span class="toggle">Jan</span>
</li>
You can use PowerShell.
New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar
or toCalendar
(as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat
is used to convert Strings to Dates (parse()
) or Dates to Strings (format()
). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
there are many causes such as
To examine the problem in detail, you can use Wireshark.
or you can just re-request or re-connect again.
If I understand you correctly, you can use a combination of Series.isin()
and DataFrame.append()
:
In [80]: df1
Out[80]:
rating user_id
0 2 0x21abL
1 1 0x21abL
2 1 0xdafL
3 0 0x21abL
4 4 0x1d14L
5 2 0x21abL
6 1 0x21abL
7 0 0xdafL
8 4 0x1d14L
9 1 0x21abL
In [81]: df2
Out[81]:
rating user_id
0 2 0x1d14L
1 1 0xdbdcad7
2 1 0x21abL
3 3 0x21abL
4 3 0x21abL
5 1 0x5734a81e2
6 2 0x1d14L
7 0 0xdafL
8 0 0x1d14L
9 4 0x5734a81e2
In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)
In [83]: ind
Out[83]:
0 True
1 False
2 True
3 True
4 True
5 False
6 True
7 True
8 True
9 False
Name: user_id, dtype: bool
In [84]: df1[ind].append(df2[ind])
Out[84]:
rating user_id
0 2 0x21abL
2 1 0xdafL
3 0 0x21abL
4 4 0x1d14L
6 1 0x21abL
7 0 0xdafL
8 4 0x1d14L
0 2 0x1d14L
2 1 0x21abL
3 3 0x21abL
4 3 0x21abL
6 2 0x1d14L
7 0 0xdafL
8 0 0x1d14L
This is essentially the algorithm you described as "clunky", using idiomatic pandas
methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1
and df2
have no overlapping row indices, i.e., if
In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')
In fact, it won't give the expected output if their row indices are not equal.
Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.
Let's stick to the solution from the linked question (Changing color scale in seaborn bar plot). You want to use argsort to determine the order of the colors to use for colorizing the bars. In the linked question argsort is applied to a Series object, which works fine, while here you have a DataFrame. So you need to select one column of that DataFrame to apply argsort on.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = sns.load_dataset("tips")
groupedvalues=df.groupby('day').sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["total_bill"].argsort().argsort()
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette=np.array(pal[::-1])[rank])
for index, row in groupedvalues.iterrows():
g.text(row.name,row.tip, round(row.total_bill,2), color='black', ha="center")
plt.show()
rank()
starts at 1
instead of zero. So one has to subtract 1 from the array. Also for indexing we need integer values, so we need to cast it to int
.
rank = groupedvalues['total_bill'].rank(ascending=True).values
rank = (rank-1).astype(np.int)
Set below code in RouteConfig.cs in App_Start folder
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}
IF still not working then do below steps
Second Way : You simple follow below steps,
1) Right click on your Project
2) Select Properties
3) Select Web option and then Select Specific Page (Controller/View) and then set your login page
Here, Account is my controller and Login is my action method (saved in Account Controller)
Please take a look attached screenshot.
_x000D_
_x000D_
/* add javascript*/_x000D_
{_x000D_
document.getElementById('abc 1').style.display='none';_x000D_
}_x000D_
/* after that add html*/_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>...</title>_x000D_
</head>_x000D_
<body>_x000D_
<table border = 2>_x000D_
<tr id = "abc 1">_x000D_
<td>abcd</td>_x000D_
</tr>_x000D_
<tr id ="abc 2">_x000D_
<td>efgh</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
this.state.myArray.push('new value')
returns the length of the extended array, instead of the array itself.Array.prototype.push().
I guess you expect the returned value to be the array.
It seems it's rather the behaviour of React:
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.React.Component.
I guess, you would do it like this (not familiar with React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
You can access this list everytime you want (even if you don't have Internet access) through:
rails generate model -h
In the spirit of functional programming, let's make our components a bit easier to work with by using abstractions.
// converts components into mappable functions
var mappable = function(component){
return function(x, i){
return component({key: i}, x);
}
}
// maps on 2-dimensional arrays
var map2d = function(m1, m2, xss){
return xss.map(function(xs, i, arr){
return m1(xs.map(m2), i, arr);
});
}
var td = mappable(React.DOM.td);
var tr = mappable(React.DOM.tr);
var th = mappable(React.DOM.th);
Now we can define our render like this:
render: function(){
return (
<table>
<thead>{this.props.titles.map(th)}</thead>
<tbody>{map2d(tr, td, this.props.rows)}</tbody>
</table>
);
}
An alternative to our map2d would be a curried map function, but people tend to shy away from currying.
For Swift 4+ versions, please use the below code:
UIDevice.current.name
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$
BEGIN
EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ sch.foo (
id serial NOT NULL,
demo_column varchar NOT NULL,
demo_column2 varchar NOT NULL,
CONSTRAINT pk_sch_foo PRIMARY KEY (id));
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON sch.foo(demo_column);
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON sch.foo(demo_column2);'
WHERE NOT EXISTS(SELECT * FROM information_schema.tables
WHERE table_schema = 'sch'
AND table_name = 'foo');
EXCEPTION WHEN null_value_not_allowed THEN
WHEN duplicate_table THEN
WHEN others THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
END; $$ LANGUAGE plpgsql;
For Mac + Android Studio 2.1, I found the best way is to save the image and then copy (cmd + c
) the image file in Finder and then click on the the drawable
directory and cmd + v
to paste in that directory. Copying the image directly from a website using cmd + c
(or right click then copy) doesn't seem to work.
In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.
Just as a random example:
// The callback interface
interface MyCallback {
void callbackCall();
}
// The class that takes the callback
class Worker {
MyCallback callback;
void onEvent() {
callback.callbackCall();
}
}
// Option 1:
class Callback implements MyCallback {
void callbackCall() {
// callback code goes here
}
}
worker.callback = new Callback();
// Option 2:
worker.callback = new MyCallback() {
void callbackCall() {
// callback code goes here
}
};
I probably messed up the syntax in option 2. It's early.
For iPad development I am using:
if (window.Touch)
{
alert("touchy touchy");
}
else
{
alert("no touchy touchy");
}
I can then selectively bind to the touch based events (eg ontouchstart) or mouse based events (eg onmousedown). I haven't yet tested on android.
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
In theory, according to RFC 4329, application/javascript
.
The reason it is supposed to be application
is not anything to do with whether the type is readable or executable. It's because there are custom charset-determination mechanisms laid down by the language/type itself, rather than just the generic charset
parameter. A subtype of text
should be capable of being transcoded by a proxy to another charset, changing the charset parameter. This is not true of JavaScript because:
a. the RFC says user-agents should be doing BOM-sniffing on the script to determine type (I'm not sure if any browsers actually do this though);
b. browsers use other information—the including page's encoding and in some browsers the script charset
attribute—to determine the charset. So any proxy that tried to transcode the resource would break its users. (Of course in reality no-one ever uses transcoding proxies anyway, but that was the intent.)
Therefore the exact bytes of the file must be preserved exactly, which makes it a binary application
type and not technically character-based text
.
For the same reason, application/xml
is officially preferred over text/xml
: XML has its own in-band charset signalling mechanisms. And everyone ignores application
for XML, too.
text/javascript
and text/xml
may not be the official Right Thing, but there are what everyone uses today for compatibility reasons, and the reasons why they're not the right thing are practically speaking completely unimportant.
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
Removing files using rm
is not a problem per se, but if you then want to commit that the file was removed, you will have to do a git rm
anyway, so you might as well do it that way right off the bat.
Also, depending on your shell, doing git rm
after having deleted the file, you will not get tab-completion so you'll have to spell out the path yourself, whereas if you git rm
while the file still exists, tab completion will work as normal.
Custom format
[>=1000]#,##0,"K";0
will give you:
Note the comma between the zero and the "K". To display millions or billions, use two or three commas instead.
In Swift 4 You can use
->Go Info.plist
-> Click plus of Information properties list
->Add App Transport Security Settings as dictionary
-> Click Plus icon App Transport Security Settings
-> Add Allow Arbitrary Loads set YES
Bellow image look like
To add second message you need to -
IEnumerable<T> items = new T[]{new T("msg")};
items = items.Concat(new[] {new T("msg2")})
even adding a return statement brings up this exception, for which only solution is this code:
if(!response.isCommitted())
// Place another redirection
jsonObj.profile-id
is a subtraction expression (i.e. jsonObj.profile - id
).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
SOAP currently has the advantage of better tools where they will generate a lot of the boilerplate code for both the service layer as well as generating clients from any given WSDL.
REST is simpler, can be easier to maintain as a result, lies at the heart of Web architecture, allows for better protocol visibility, and has been proven to scale at the size of the WWW itself. Some frameworks out there help you build REST services, like Ruby on Rails, and some even help you with writing clients, like ADO.NET Data Services. But for the most part, tool support is lacking.
I had the same problem and solved it adding "es5" library to tsconfig.json like this:
{
"compilerOptions": {
"target": "es5", //defines what sort of code ts generates, es5 because it's what most browsers currently UNDERSTANDS.
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true, //for angular to be able to use metadata we specify in our components.
"experimentalDecorators": true, //angular needs decorators like @Component, @Injectable, etc.
"removeComments": false,
"noImplicitAny": false,
"lib": [
"es2016",
"dom",
"es5"
]
}
}
I found the solution:
In your activity which has the Theme.Dialog
style set, do this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
It's important that you call Window.setLayout()
after you call setContentView()
, otherwise it won't work.
Why do you want a textarea to submit when you hit enter?
A "text" input will submit by default when you press enter. It is a single line input.
<input type="text" value="...">
A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.
<textarea name="area"></textarea>
You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.
WHERE clause does not work for aggregate functions
means : you should not use like this
bonus : table name
SELECT name
FROM bonus
GROUP BY name
WHERE sum(salary) > 200
HERE Instead of using WHERE clause you have to use HAVING..
without using GROUP BY clause, HAVING clause just works as WHERE clause
SELECT name
FROM bonus
GROUP BY name
HAVING sum(salary) > 200
Simplest working solution for flow window (tested at Chrome):
<form action='...' method=post target="result" onsubmit="window.open('','result','width=800,height=400');">
<input name="..">
....
</form>
for a in soup("p",{'id':'pagination'})[0]("a",{'href': True}):
if createunicode(a.text) in ['<','<']:
links.append(a.attrMap['href'])
else:
continue
It works for me.
Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method
http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3
The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:
{"list":[
{"value": 1, "label": "abc"},
{"value": 2, "label": "def"},
{"value": 3, "label": "ghi"}
]}
Then on the source portion of the autocomplete method:
source: function(request, response) {
$.getJSON("listing.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.list, function(m) {
return {
label: m.label,
value: m.value
};
});
response(array);
});
},
select: function (event, ui) {
$("#autocomplete_field").val(ui.item.label); // display the selected text
$("#field_id").val(ui.item.value); // save selected id to hidden input
return false;
}
Hope this helps... all the best!
If anyone is trying to use jQuery Mobile on Android and has problems with JQM swipe detection
(I had some on Xperia Z1, Galaxy S3, Nexus 4 and some Wiko phones too) this can be useful :
//Fix swipe gesture on android
if(android){ //Your own device detection here
$.event.special.swipe.verticalDistanceThreshold = 500
$.event.special.swipe.horizontalDistanceThreshold = 10
}
Swipe on android wasn't detected unless it was a very long, precise and fast swipe.
With these two lines it works correctly
Of the options you asked about:
float:left;
float
concept was poorly designed in the CSS specs. Nothing we can do about that now though. But the important thing is it does work, and it works in all browsers (even IE6/7), so use it if you like it.The additional markup for clearing may not be necessary if you use the :after
selector to clear the floats, but this isn't an option if you want to support IE6 or IE7.
display:inline;
This shouldn't be used for layout, with the exception of IE6/7, where display:inline; zoom:1
is a fall-back hack for the broken support for inline-block
.
display:inline-block;
This is my favourite option. It works well and consistently across all browsers, with a caveat for IE6/7, which support it for some elements. But see above for the hacky solution to work around this.
The other big caveat with inline-block
is that because of the inline aspect, the white spaces between elements are treated the same as white spaces between words of text, so you can get gaps appearing between elements. There are work-arounds to this, but none of them are ideal. (the best is simply to not have any spaces between the elements)
display:table-cell;
table-cell
is designed to be used in a context of being inside elements that are styled as table
and table-row
; using table-cell
in isolation is not the intended way to do it, so you may experience different browsers treating it differently.Other techniques you may have missed? Yes.
Since you say this is for a multi-column layout, there is a CSS Columns feature that you might want to know about. However it isn't the most well supported feature (not supported by IE even in IE9, and a vendor prefix required by all other browsers), so you may not want to use it. But it is another option, and you did ask.
There's also CSS FlexBox feature, which is intended to allow you to have text flowing from box to box. It's an exciting feature that will allow some complex layouts, but this is still very much in development -- see http://html5please.com/#flexbox
Hope that helps.
Alliteratively you can try placing a Label control and placing it on top of the progress bar control. Then you can set whatever the text you want to the label. I haven't done this my self. If it works it should be a simpler solution than overriding onpaint.
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
Like other said you can't use the "-" in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path
For example if your structure is like this:
foo-bar
+-- barfoo.py
+-- __init__.py
import sys
sys.path.append('foo-bar')
import barfoo
Append suffix L
: 23423429L
.
By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L
for long values.
You need some sort of Inter Process Communication. Use a pipe or a shared buffer.
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });
If you're dealing with multiple (html 5) file uploads, I took the top suggested comment and modified it a little:
var files = $('#file1')[0].files;
var len = $('#file1').get(0).files.length;
for (var i = 0; i < len; i++) {
f = files[i];
var ext = f.name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('invalid extension!');
}
}
non jQuery quick and dirty answer:
function setChangeListener (div, listener) {
div.addEventListener("blur", listener);
div.addEventListener("keyup", listener);
div.addEventListener("paste", listener);
div.addEventListener("copy", listener);
div.addEventListener("cut", listener);
div.addEventListener("delete", listener);
div.addEventListener("mouseup", listener);
}
var div = document.querySelector("someDiv");
setChangeListener(div, function(event){
console.log(event);
});
This is what I managed to do so far. I guess this is kind of what you're trying to pull out. The only thing is that I can still not manage to assign the proper height to the container DIV.
The HTML:
<div id="container">
<div id="header">HEADER</div>
<div id="fixeddiv-top">FIXED DIV (TOP)</div>
<div id="content-container">
<div id="content">CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT</div>
</div>
<div id="fixeddiv-bottom">FIXED DIV (BOTTOM)</div>
</div>
And the CSS:
html {
height:100%;
}
body {
height:100%;
margin:0;
padding:0;
}
#container {
width:600px;
height:50%;
text-align:center;
display:block;
position:relative;
}
#header {
background:#069;
text-align:center;
width:100%;
height:80px;
}
#fixeddiv-top {
background:#AAA;
text-align:center;
width:100%;
height:20px;
}
#content-container {
height:100%;
}
#content {
text-align:center;
height:100%;
background:#F00;
margin:0 auto;
overflow:auto;
}
#fixeddiv-bottom {
background:#AAA;
text-align:center;
width:100%;
height:20px;
}
As of 2018-04-20 Git for Windows has a bug which effectively limits the file size to 4GB max using that particular implementation (this bug propagates to lfs as well).
I had to pass the default
parameter as well, like this:
print(json.dumps(my_dictionary, indent=4, default=str))
and if you want the keys sorted, then you can do:
print(json.dumps(my_dictionary, sort_keys=True, indent=4, default=str))
in order to fix this type error:
TypeError: Object of type 'datetime' is not JSON serializable
which caused by datetimes being some values in the dictionary.
The simplest (not the best or ideal) solution I found was to use react-native-dotenv. You simply add the "react-native-dotenv" preset to your .babelrc
file at the project root like so:
{
"presets": ["react-native", "react-native-dotenv"]
}
Create a .env
file and add properties:
echo "SOMETHING=anything" > .env
Then in your project (JS):
import { SOMETHING } from 'react-native-dotenv'
console.log(SOMETHING) // "anything"
I think what you want to do is
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
Exits the loop if the line is empty(Improving code).
#include <stdio.h>
#include <string.h>
// The value BUFFERSIZE can be changed to customer's taste . Changes the
// size of the base array (string buffer )
#define BUFFERSIZE 10
int main(void)
{
char buffer[BUFFERSIZE];
char cChar;
printf("Enter a message: \n");
while(*(fgets(buffer, BUFFERSIZE, stdin)) != '\n')
{
// For concatenation
// fgets reads and adds '\n' in the string , replace '\n' by '\0' to
// remove the line break .
/* if(buffer[strlen(buffer) - 1] == '\n')
buffer[strlen(buffer) - 1] = '\0'; */
printf("%s", buffer);
// Corrects the error mentioned by Alain BECKER.
// Checks if the string buffer is full to check and prevent the
// next character read by fgets is '\n' .
if(strlen(buffer) == (BUFFERSIZE - 1) && (buffer[strlen(buffer) - 1] != '\n'))
{
// Prevents end of the line '\n' to be read in the first
// character (Loop Exit) in the next loop. Reads
// the next char in stdin buffer , if '\n' is read and removed, if
// different is returned to stdin
cChar = fgetc(stdin);
if(cChar != '\n')
ungetc(cChar, stdin);
// To print correctly if '\n' is removed.
else
printf("\n");
}
}
return 0;
}
Exit when Enter is pressed.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#define BUFFERSIZE 16
int main(void)
{
char buffer[BUFFERSIZE];
printf("Enter a message: \n");
while(true)
{
assert(fgets(buffer, BUFFERSIZE, stdin) != NULL);
// Verifies that the previous character to the last character in the
// buffer array is '\n' (The last character is '\0') if the
// character is '\n' leaves loop.
if(buffer[strlen(buffer) - 1] == '\n')
{
// fgets reads and adds '\n' in the string, replace '\n' by '\0' to
// remove the line break .
buffer[strlen(buffer) - 1] = '\0';
printf("%s", buffer);
break;
}
printf("%s", buffer);
}
return 0;
}
Concatenation and dinamic allocation(linked list) to a single string.
/* Autor : Tiago Portela
Email : [email protected]
Sobre : Compilado com TDM-GCC 5.10 64-bit e LCC-Win32 64-bit;
Obs : Apenas tentando aprender algoritimos, sozinho, por hobby. */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#define BUFFERSIZE 8
typedef struct _Node {
char *lpBuffer;
struct _Node *LpProxNode;
} Node_t, *LpNode_t;
int main(void)
{
char acBuffer[BUFFERSIZE] = {0};
LpNode_t lpNode = (LpNode_t)malloc(sizeof(Node_t));
assert(lpNode!=NULL);
LpNode_t lpHeadNode = lpNode;
char* lpBuffer = (char*)calloc(1,sizeof(char));
assert(lpBuffer!=NULL);
char cChar;
printf("Enter a message: \n");
// Exit when Enter is pressed
/* while(true)
{
assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
assert(lpNode->lpBuffer!=NULL);
strcpy(lpNode->lpBuffer, acBuffer);
if(lpNode->lpBuffer[strlen(acBuffer) - 1] == '\n')
{
lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
lpNode->LpProxNode = NULL;
break;
}
lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
lpNode = lpNode->LpProxNode;
assert(lpNode!=NULL);
}*/
// Exits the loop if the line is empty(Improving code).
while(true)
{
assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
assert(lpNode->lpBuffer!=NULL);
strcpy(lpNode->lpBuffer, acBuffer);
if(acBuffer[strlen(acBuffer) - 1] == '\n')
lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
if(strlen(acBuffer) == (BUFFERSIZE - 1) && (acBuffer[strlen(acBuffer) - 1] != '\n'))
{
cChar = fgetc(stdin);
if(cChar != '\n')
ungetc(cChar, stdin);
}
if(acBuffer[0] == '\n')
{
lpNode->LpProxNode = NULL;
break;
}
lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
lpNode = lpNode->LpProxNode;
assert(lpNode!=NULL);
}
printf("\nPseudo String :\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
printf("%s", lpNode->lpBuffer);
lpNode = lpNode->LpProxNode;
}
printf("\n\nMemory blocks:\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
printf("Block \"%7s\" size = %lu\n", lpNode->lpBuffer, (long unsigned)(strlen(lpNode->lpBuffer) + 1));
lpNode = lpNode->LpProxNode;
}
printf("\nConcatenated string:\n");
lpNode = lpHeadNode;
while(lpNode != NULL)
{
lpBuffer = (char*)realloc(lpBuffer, (strlen(lpBuffer) + strlen(lpNode->lpBuffer)) + 1);
strcat(lpBuffer, lpNode->lpBuffer);
lpNode = lpNode->LpProxNode;
}
printf("%s", lpBuffer);
printf("\n\n");
// Deallocate memory
lpNode = lpHeadNode;
while(lpNode != NULL)
{
lpHeadNode = lpNode->LpProxNode;
free(lpNode->lpBuffer);
free(lpNode);
lpNode = lpHeadNode;
}
lpBuffer = (char*)realloc(lpBuffer, 0);
lpBuffer = NULL;
if((lpNode == NULL) && (lpBuffer == NULL))
{
printf("Deallocate memory = %s", (char*)lpNode);
}
printf("\n\n");
return 0;
}
No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.
Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.
Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...
Here I'll explain what I mean:
<input type="hidden" value="{"name":"John"}">
As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:
<input type="hidden" value="{" rubbish >
So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:
> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"
Now that value can be safely stored in an input hidden type like so:
<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">
or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:
<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>
Now to read the data back we can do something like:
> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}
In simple way, Its not possible. Because DropdownList
contain ListItem
and it will be selected by default
But, you can use ValidationControl
for that:
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
ListViewItem.IsSelected = true;
ListViewItem.Focus();
string domainName = Request.Url.Host
There's nothing inherently wrong with testing threaded/async code, particularly if threading is the point of the code you're testing. The general approach to testing this stuff is to:
But that's a lot of boilerplate for one test. A better/simpler approach is to just use ConcurrentUnit:
final Waiter waiter = new Waiter();
new Thread(() -> {
doSomeWork();
waiter.assertTrue(true);
waiter.resume();
}).start();
// Wait for resume() to be called
waiter.await(1000);
The benefit of this over the CountdownLatch
approach is that it's less verbose since assertion failures that occur in any thread are properly reported to the main thread, meaning the test fails when it should. A writeup that compares the CountdownLatch
approach to ConcurrentUnit is here.
I also wrote a blog post on the topic for those who want to learn a bit more detail.
parseInt()
should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10
in parseInt(number, 10)
specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt
.