AFAIK, You have to use image function imagecreatefromstring, imagejpeg to create the images.
$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
Hope this will help.
PHP CODE WITH IMAGE DATA
$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
So Following is the php part of your program .. NOTE
the change with comment Change is here
$uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
foreach ($uploadedPhotos as $file) {
if($this->input->post($file)){
$imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
$photo = imagecreatefromstring($imageData); // <-- **Change is here**
/* Set name of the photo for show in the form */
$this->session->set_userdata('upload_'.$file,'ant');
/*set time of the upload*/
if(!$this->session->userdata('uploading_on_datetime')){
$this->session->set_userdata('uploading_on_datetime',time());
}
$datetime_upload = $this->session->userdata('uploading_on_datetime',true);
/* create temp dir with time and user id */
$new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
if(!is_dir($new_dir)){
@mkdir($new_dir);
}
/* move uploaded file with new name */
// @file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**
}
}
Your regex is good altough I would replace it with the empty string
String resultString = subjectString.replaceAll("[\t\n\r]", "");
You expect a space between "text." and "And" right?
I get that space when I try the regex by copying your sample
"This is my text. "
So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.
<a href="<?php echo site_url('controller/function'); ?>Compose</a>
<a href="<?php echo site_url('controller/function'); ?>Inbox</a>
<a href="<?php echo site_url('controller/function'); ?>Outbox</a>
<a href="<?php echo site_url('controller/function'); ?>logout</a>
<a href="<?php echo site_url('controller/function'); ?>logout</a>
I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.
In TextPad's replace dialog, turn on regex; then you could try replacing
<row id="1"/>
by
<row id="\i"/>
Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/
One the elements are added, use the rules method to add the rules
//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
$(this).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
})
Demo: Fiddle
Update
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
var $li = $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
$('#FileUpload' + filenumber).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
filenumber++;
return false;
});
You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.
For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.
Does not equal. The opposite of =
, equivalent to !=
.
Also, for everyone's info, this can return a non-zero number of rows. I see the OP has reformatted his question so it's a bit clearer, but as far as I can tell, this finds records where product ID is among those found in order #605, as is quantity, but it's not actually order #605. If order #605 contains 1 apple, 2 bananas and 3 crayons, #604 should match if it contains 2 apples (but not 3 dogs). It just won't match order #605. (And if ordid
is unique, then it would find exact duplicates.)
If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1"
as true
and anything else as false
(as Kevin does). If you wanted the conversion to fail if anything other than "1"
or "0"
is returned, then the following would suffice (you could put it in a helper method):
if (returnValue == "1")
{
return true;
}
else if (returnValue == "0")
{
return false;
}
else
{
throw new FormatException("The string is not a recognized as a valid boolean value.");
}
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv
:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv
and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Subtracting the Minimum of the ends of the ranges from the Maximum of the beginning seems to do the trick. If the result is less than or equal to zero, we have an overlap. This visualizes it well:
Here´s something I tried. Basically, I put the "flexible" content (the td which contains lines that are too long) in a div container that´s one line high, with hidden overflow. Then I let the text wrap into the invisible. You get breaks at wordbreaks though, not just a smooth cut-off.
table {
width: 100%;
}
.hideend {
white-space: normal;
overflow: hidden;
max-height: 1.2em;
min-width: 50px;
}
.showall {
white-space:nowrap;
}
<table>
<tr>
<td><div class="showall">Show all</div></td>
<td>
<div class="hideend">Be a bit flexible about hiding stuff in a long sentence</div>
</td>
<td>
<div class="showall">Show all this too</div>
</td>
</tr>
</table>
The -p
flag of netstat
gives you PID of the process:
netstat -l -p
Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat
.
As we worked out during the discussion with @Cyclone, the line that does the job is:
sockstat -4 -l | grep :80 | awk '{print $3}' | head -1
I am the original poster and I accepted the above answer by DGH without having first used it in the code.
Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).
I thought it was worth posting the tweak here for the benefit of others:
try:
a = Application("abcdef", "")
except pySourceAidExceptions.PathIsNotAValidOne:
pass
except:
self.assertTrue(False)
What I was attempting to do here was to ensure that if an attempt was made to instantiate an Application object with a second argument of spaces the pySourceAidExceptions.PathIsNotAValidOne would be raised.
I believe that using the above code (based heavily on DGH's answer) will do that.
Why not just use a CDN? Unless you need to edit the code of BS, then you just need to reference the codes in CDN.
See BS 4 CDN Here:
https://www.w3schools.com/bootstrap4/bootstrap_get_started.asp
At the bottom of the page.
<div style="width:100%;">
<div style="margin-left:45px;">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
Based on the answer of @Cogwheel i want to share a modified solution that works for SSIS and the "Script Component":
Place this code in the right method:
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string email = Row.fieldName;
try
{
System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email);
Row.fieldName= addr.Address.ToString();
}
catch
{
Row.fieldName = "WRONGADDRESS";
}
}
Then you can use a Conditional Split to filter out all invalid records or whatever you want to do.
try this new DecimalFormat("#.00");
update:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
Your code wasn't using the decimalformat correctly
The 0 in the pattern means an obligatory digit, the # means optional digit.
update 2: check bellow answer
If you want 0.2677
formatted as 0.27
you should use new DecimalFormat("0.00");
otherwise it will be .27
Use a normalised colour histogram. (Read the section on applications here), they are commonly used in image retrieval/matching systems and are a standard way of matching images that is very reliable, relatively fast and very easy to implement.
Essentially a colour histogram will capture the colour distribution of the image. This can then be compared with another image to see if the colour distributions match.
This type of matching is pretty resiliant to scaling (once the histogram is normalised), and rotation/shifting/movement etc.
Avoid pixel-by-pixel comparisons as if the image is rotated/shifted slightly it may lead to a large difference being reported.
Histograms would be straightforward to generate yourself (assuming you can get access to pixel values), but if you don't feel like it, the OpenCV library is a great resource for doing this kind of stuff. Here is a powerpoint presentation that shows you how to create a histogram using OpenCV.
USE AdventureWorks2012;
GO
DBCC CHECKIDENT ('Person.AddressType', RESEED, 0);
GO
AdventureWorks2012=Your databasename
Person.AddressType=Your tablename
Group Selector
body {font-size: 12px; }
body {font-family: arial, helvetica, sans-serif;}
th {font-size: 12px; font-family: arial, helvetica, sans-serif;}
td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
Becomes this:
body, th, td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
So in your case you have tried the group selector whereas its an intersection
$(".a, .b")
instead use this
$(".a.b")
Take an array containing months name.
String[] str = {"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
Then where you wanna take month use like follow:
if(i<str.length)
monthString = str[i-1];
else
monthString = "Invalid month";
If you have deleted lot of files and folders, just do this
git commit -a -m .
git push
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}
Try:
select * from v$session where sid = SYS_CONTEXT('USERENV','SID');
You might also be interested in this AskTom post
After seing your comment, you can do:
SELECT * FROM global_name;
The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3, six
is the compatibility module. six.PY2
and six.PY3
are two booleans if you want to check the version.
However, a better solution than using a lot of if
statements is to use six
compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax for next
, someone could update six
so your old code would still work.
import six
#OK
if six.PY2:
x = it.next() # Python 2 syntax
else:
x = next(it) # Python 3 syntax
#Better
x = six.next(it)
Cheers
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
[solved]
#copy all the code below:
#save file as .ps1 run and see the magic
Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
(Get-CimInstance Win32_OperatingSystem).version
#-------------comment-------------#
#-----finding windows version-----#
$version= (Get-CimInstance Win32_OperatingSystem).version
$length= $version.Length
$index= $version.IndexOf(".")
[int]$windows= $version.Remove($index,$length-2)
$windows
#-----------end------------------#
#-----------comment-----------------#
I have handled back and Home button in Navigation Drawer like
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
NavigationView navigationView;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
//showing first fragment on Start
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//listener for home
if(id==android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Begin the transaction
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_companies_list) {
fragment = new FirstFragment();
// Handle the action
}
// Begin the transaction
if(fragment!=null){
if(item.isChecked()){
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.WikiCompany, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
drawerToggle.setDrawerIndicatorEnabled(false);
else
drawerToggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
and In each onViewCreated
I call
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).updateDrawerIcon();
((HomeActivity) getActivity()).setActionBarTitle("List");
}
There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:
with open(filename, 'r') as f:
next(f)
for line in f:
and:
with open(filename,'r') as f:
lines = f.readlines()[1:]
The main use for partial classes is with generated code. If you look at the WPF (Windows Presentation Foundation) network, you define your UI with markup (XML). That markup is compiled into partial classes. You fill in code with partial classes of your own.
Webpack and Browserify do pretty much the same job, which is processing your code to be used in a target environment (mainly browser, though you can target other environments like Node). Result of such processing is one or more bundles - assembled scripts suitable for targeted environment.
For example, let's say you wrote ES6 code divided into modules and want to be able to run it in a browser. If those modules are Node modules, the browser won't understand them since they exist only in the Node environment. ES6 modules also won't work in older browsers like IE11. Moreover, you might have used experimental language features (ES next proposals) that browsers don't implement yet so running such script would just throw errors. Tools like Webpack and Browserify solve these problems by translating such code to a form a browser is able to execute. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.
However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but using both leads to very similar results. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.
Webpack Dev Server provides a similar solution to Browsersync - a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately, with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.
I've been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.
While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running rimraf for cleaning purposes) might be more challenging. But in the majority of cases, those three are equal in terms of their results.
As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in package.json
in the root folder, in a property named scripts
. There you will mostly encounter commands like babel-node tools/run start
. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file tools/run
(run.js file located in tools) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case is start
- another utility (start.js
) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).
Speaking more precisely, start.js
creates both client and server side bundles, starts an express server and after a successful launch initializes Browser-sync, which at the time of writing looked like this (please refer to react starter project for the newest code).
const bs = Browsersync.create();
bs.init({
...(DEBUG ? {} : { notify: false, ui: false }),
proxy: {
target: host,
middleware: [wpMiddleware, ...hotMiddlewares],
},
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: ['build/content/**/*.*'],
}, resolve)
The important part is proxy.target
, where they set server address they want to proxy, which could be http://localhost:3000, and Browsersync starts a server listening on http://localhost:3001, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property files
with individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.
Now I don't have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like
gulp.task('bundle', function() {
// bundling source files with some gulp plugins like gulp-webpack maybe
});
gulp.task('start', function() {
// starting server and stuff
});
where you would be doing essentially pretty much the same things as in the starter-kit, this time with task runner, which solves some problems for you, but presents its own issues and some difficulties during learning the usage, and as I say, the more dependencies you have, the more can go wrong. And that is the reason I like to get rid of such tools.
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
DA is right. In your own fiddle, the iframe is indeed responsive. You can verify that in firebug by checking iframe box-sizing. But some elements inside that iframe is not responsive, so they "stick out" when window size is small. For example, div#products-post-wrapper
's width is 8800px.
I find, that psql show password prompt even you define PGPASSWORD variable, but you can specify -w option for psql to omit password prompt.
Yes. The only way would be to drop the constraint with an Alter table then recreate it.
ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>
ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)
Please try this
<!DOCTYPE html>
<html>
<head>
<title>Jquery</title>
<meta charset="utf-8">
<script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
</head>
<body>
<input type="text" id="message" value="" />
<input type="button" id="sendButton" value="Send">
<script>
$(document).ready(function(){
var checkField;
//checking the length of the value of message and assigning to a variable(checkField) on load
checkField = $("input#message").val().length;
var enableDisableButton = function(){
if(checkField > 0){
$('#sendButton').removeAttr("disabled");
}
else {
$('#sendButton').attr("disabled","disabled");
}
}
//calling enableDisableButton() function on load
enableDisableButton();
$('input#message').keyup(function(){
//checking the length of the value of message and assigning to the variable(checkField) on keyup
checkField = $("input#message").val().length;
//calling enableDisableButton() function on keyup
enableDisableButton();
});
});
</script>
</body>
</html>
For those who are interested in using react hooks
, this might help you get started.
import React, { useState, useEffect, useRef } from 'react'
export default () => {
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() => {
setHeight(ref.current.clientHeight)
})
return (
<div ref={ref}>
{height}
</div>
)
}
Try this:
Update TableB Set
Code = Coalesce(
(Select Max(Value)
From TableA
Where Id = b.Id), 123)
From TableB b
This error can be resolved by adding MessageBoxOptions.ServiceNotification
.
MessageBox.Show(msg, "Print Error", System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
System.Windows.Forms.MessageBoxOptions.ServiceNotification);
But it is not going to show any dialog box if your web application is installed on IIS or server.Because in IIS or server it is hosted on worker process which dont have any desktop.
This nodejs code just do that , as @Felix Yan mentioned former way seems to work just fine , i had some issues with other snipets hope this helps.
This will rename column "oldColumnName" to be "newColumnName" of table "documents"
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
//var url = 'mongodb://localhost:27017/myproject';
var url = 'mongodb://myuser:[email protected]:portNumber/databasename';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
renameDBColumn(db, function() {
db.close();
});
});
//
// This function should be used for renaming a field for all documents
//
var renameDBColumn = function(db, callback) {
// Get the documents collection
console.log("renaming database column of table documents");
//use the former way:
remap = function (x) {
if (x.oldColumnName){
db.collection('documents').update({_id:x._id}, {$set:{"newColumnName":x.oldColumnName}, $unset:{"oldColumnName":1}});
}
}
db.collection('documents').find().forEach(remap);
console.log("db table documents remap successfully!");
}
Ajax.BeginForm looks to be a fail.
Using a regular Html.Begin for, this does the trick just nicely:
$('#detailsform').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(r) {
$("#edit").html(r);
});
});
I ended up using the below snippet and it works in most browsers, not tested in IE though.
let data = JSON.stringify([{email: "[email protected]", name: "test"}, {email: "[email protected]", name: "anothertest"}]);_x000D_
_x000D_
let type = "application/json", name = "testfile.json";_x000D_
downloader(data, type, name)_x000D_
_x000D_
function downloader(data, type, name) {_x000D_
let blob = new Blob([data], {type});_x000D_
let url = window.URL.createObjectURL(blob);_x000D_
downloadURI(url, name);_x000D_
window.URL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
function downloadURI(uri, name) {_x000D_
let link = document.createElement("a");_x000D_
link.download = name;_x000D_
link.href = uri;_x000D_
link.click();_x000D_
}
_x000D_
function downloadURI(uri, name) {
let link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
function downloader(data, type, name) {
let blob = new Blob([data], {type});
let url = window.URL.createObjectURL(blob);
downloadURI(url, name);
window.URL.revokeObjectURL(url);
}
i fixed this by modifying php.ini
file at C:\wamp\bin\apache\apache2.4.9\bin\
curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"
first i was trying by modifying php.ini
file at C:\wamp\bin\php\php5.5.12\
and it didn't work.
hope this helps someone who is searching for the right php.ini
to modify
aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...
Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:
https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new
The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.
For instance, where I had:
$_SERVER['SERVER_NAME']
I've put instead:
filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)
You have the filter_input and filters doc here:
Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:
xx <- reshape(df, idvar=c("skew","version","color"),
v.names="price", timevar="product", direction="wide")
xx will have columns price.p1, ... price.p4, so:
ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
geom_point(shape=19, size=5)
ggp + facet_grid(color~version)
gives the result from your image.
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
In android studio 3.0 they have introduced android-profiler to help you to understand how your app uses CPU, memory, network, and battery resources.
https://developer.android.com/studio/profile/android-profiler
Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title> Temperature Selection </title>_x000D_
<!-- css -->_x000D_
<link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="css/main.css">_x000D_
_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
<script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
<script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
<script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
<script src="js/library.js"> </script>_x000D_
<script src="js/sfds.js"> </script>_x000D_
_x000D_
<script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--TODO: need to integrate this code into the project:-->_x000D_
<script type="text/javascript">_x000D_
function changeImage(a) {_x000D_
document.getElementById("img").src=a;_x000D_
}_x000D_
</script>_x000D_
<script>_x000D_
_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
$("#ambient").click(function(event){_x000D_
var $this= $(this);_x000D_
if($this.hasClass('clicked')){_x000D_
$this.removeClass('clicked');_x000D_
SFDS.setTemperatureType(0);_x000D_
$this.find('h2').text('Select Ambient Temperature 21 Degrees C');_x000D_
<!--added on 05/20/2015-->_x000D_
}else{_x000D_
SFDS.setTemperatureType(1);_x000D_
$this.addClass('clicked');_x000D_
$this.find('h2').text('Ambient Temperature 21 Degrees C Selected');_x000D_
_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
$("#body").click(function(event){_x000D_
var $this= $(this);_x000D_
if($this.hasClass('clicked')){_x000D_
$this.removeClass('clicked');_x000D_
SFDS.setTemperatureType(0);_x000D_
$this.find('h2').text('Select Body Temperature 37 Degrees C');_x000D_
<!--added on 05/20/2015-->_x000D_
}else{_x000D_
SFDS.setTemperatureType(1);_x000D_
$this.addClass('clicked');_x000D_
$this.find('h2').text('Body Temperature 37 Degrees C Selected');_x000D_
_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
});_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
<header>_x000D_
<div class="row">_x000D_
<div class="col-xs-6">_x000D_
<div id="date"><span class="date_time"></span></div>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
</div>_x000D_
</div>_x000D_
</header>_x000D_
<div class="row">_x000D_
<div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
<div id="temperature" class="main_button center-block">_x000D_
<div class="large_circle_button"> _x000D_
<h2>Select<br/>Temperature</h2>_x000D_
<img class="center-block large_button_image" src="images/thermometer.png" alt=""> _x000D_
<!-- TODO <img src='images/dropsterilewater.png' onclick='changeImage("images/dropsterilewater.png");'>_x000D_
<img src='images/imagecansterilesaline.png' onclick='changeImage("images/imagecansterilesaline.png");'>-->_x000D_
</div>_x000D_
<h1></h1>_x000D_
</div>_x000D_
</div>_x000D_
<div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
<div class="row">_x000D_
<div class="col-xs-12">_x000D_
<div id="ambient" class="large_rectangle_button">_x000D_
<div class="label_wrapper">_x000D_
<h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>_x000D_
</div>_x000D_
<div class="image_wrapper">_x000D_
<img src="images/house.png" alt="" class="ambient_temp_image">_x000D_
</div>_x000D_
<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-12">_x000D_
<div id="body" class="large_rectangle_button">_x000D_
<div class="label_wrapper">_x000D_
<h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>_x000D_
</div>_x000D_
<div class="image_wrapper">_x000D_
<img src="images/bodytempman.png" alt="" class="body_temp_image">_x000D_
</div>_x000D_
<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
<div class="container-fluid">_x000D_
<div class="row cols-bottom">_x000D_
<div class="col-sm-3">_x000D_
<a href="main.html">_x000D_
<div class="small_circle_button"> _x000D_
<img src="images/buttonback.png" alt="back to home" class="settings"/> <!-- width="49" height="48" -->_x000D_
</div>_x000D_
</div></a><div class=" col-sm-6">_x000D_
<div id="stop_button" >_x000D_
<img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
</div>_x000D_
_x000D_
</div><div class="col-sm-3">_x000D_
<div id="parker" class="pull-right">_x000D_
<img src="images/#" alt="logo" /> <!-- width="131" height="65" -->_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators:
I got this same exception because I tried to wrap more than one function with those two decorators:
@app.route("/path1")
@exception_handler
def func1():
pass
@app.route("/path2")
@exception_handler
def func2():
pass
Specifically, it is caused by trying to register a few functions with the name wrapper:
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
return wrapper
Changing the name of the function solved it for me (wrapper.__name__ = func.__name__):
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
# Renaming the function name:
wrapper.__name__ = func.__name__
return wrapper
Then, decorating more than one endpoint worked.
I'd rather use more convenient itemSelect
event. With this event you can use org.primefaces.event.SelectEvent
objects in your listener.
<p:selectOneMenu ...>
<p:ajax event="itemSelect"
update="messages"
listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>
With such listener:
public void onItemSelectedListener(SelectEvent event){
MyItem selectedItem = (MyItem) event.getObject();
//do something with selected value
}
Use the index to get desired node if xpath is complicated or more than one node present with same xpath.
Ex :
(//bookstore[@location = 'US'])[index]
You can give the number which node you want.
You can also use $.parseJSON(data)
that will explicit convert a string thats come from a PHP script to a real JSON array.
"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.
The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.
In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.
window.location.href = "/";
This worked for me. If you have multiple folders/directories, you can use this:
window.location.href = "/folder_name/";
// This one has print statement so you can see the result at every stage if you would like. They are not needed
function crop(image, width, height)
{
image.width = width;
image.height = height;
//print ("in function", image, image.getWidth(), image.getHeight());
return image;
}
var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());
EugeneXa mentioned it in a comment, but it deserves to be an answer:
var template = $("#modal_template").html().trim();
This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:
var markup = Mustache.render(template, data);
$(markup).appendTo(container);
For git 1.9.5 on Windows 7: "my Notes" (double quotes) corrected this issue. In my case putting the file(s) before or after the -m 'message'. made no difference; using single quotes was the problem.
Try this:
<div class="form-group">
<label class="control-label" for="Company">Company</label>
<select id="Company" class="form-control" name="Company">
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
</div>
tuple = 1 record; n-tuple = ordered list of 'n' records; Elmasri Navathe book (page 198 3rd edition).
record = either ordered or unordered.
If you include the additional methods file, here's the current file for 1.7: http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
You can use the lettersonly
rule :) The additional methods are part of the zip you download, you can always find the latest here.
Here's an example:
$("form").validate({
rules: {
myField: { lettersonly: true }
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate()
call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
Here's a non-jQuery version that is considerably faster than both the jQuery .html()
version and the .replace()
version. This preserves all whitespace, but like the jQuery version, doesn't handle quotes.
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
Speed: http://jsperf.com/htmlencoderegex/17
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
function htmlDecode( html ) {
var a = document.createElement( 'a' ); a.innerHTML = html;
return a.textContent;
};
document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
//sanity check
var html = '<div> & hello</div>';
document.getElementById( 'same' ).textContent =
'html === htmlDecode( htmlEncode( html ) ): '
+ ( html === htmlDecode( htmlEncode( html ) ) );
<input id="hidden" type="hidden" value="chalk & cheese" />
<input id="text" value="" />
<div id="same"></div>
Ran into the same bug here. This worked for me.
.navbar {
position: static;
}
By setting the position to static, it means the navbar will fall into the flow of the document as it normally would.
I tried experimenting with the answers given. My personal finding came out to be:
git rm -r --cached .
And then
git add .
This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.
You can use Row_Number
for limit query result.
Example:
SELECT * FROM (
select row_number() OVER (order by createtime desc) AS ROWINDEX,*
from TABLENAME ) TB
WHERE TB.ROWINDEX between 0 and 10
--
With above query, I will get PAGE 1 of results from TABLENAME
.
Using lxml:
from lxml import etree
# create XML
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)
# pretty string
s = etree.tostring(root, pretty_print=True)
print s
Output:
<root>
<child/>
<child>some text</child>
</root>
See the tutorial for more information.
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
In Chart.js version 2.0, it is possible to set labels for axes:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See Labelling documentation for more details.
There are a number of ways you can do this:
How to implement Idea #5? Well, one way is to first create an interface:
public interface ThreadCompleteListener {
void notifyOfThreadComplete(final Thread thread);
}
then create the following class:
public abstract class NotifyingThread extends Thread {
private final Set<ThreadCompleteListener> listeners
= new CopyOnWriteArraySet<ThreadCompleteListener>();
public final void addListener(final ThreadCompleteListener listener) {
listeners.add(listener);
}
public final void removeListener(final ThreadCompleteListener listener) {
listeners.remove(listener);
}
private final void notifyListeners() {
for (ThreadCompleteListener listener : listeners) {
listener.notifyOfThreadComplete(this);
}
}
@Override
public final void run() {
try {
doRun();
} finally {
notifyListeners();
}
}
public abstract void doRun();
}
and then each of your Threads will extend NotifyingThread
and instead of implementing run()
it will implement doRun()
. Thus when they complete, they will automatically notify anyone waiting for notification.
Finally, in your main class -- the one that starts all the Threads (or at least the object waiting for notification) -- modify that class to implement ThreadCompleteListener
and immediately after creating each Thread add itself to the list of listeners:
NotifyingThread thread1 = new OneOfYourThreads();
thread1.addListener(this); // add ourselves as a listener
thread1.start(); // Start the Thread
then, as each Thread exits, your notifyOfThreadComplete
method will be invoked with the Thread instance that just completed (or crashed).
Note that better would be to implements Runnable
rather than extends Thread
for NotifyingThread
as extending Thread is usually discouraged in new code. But I'm coding to your question. If you change the NotifyingThread
class to implement Runnable
then you have to change some of your code that manages Threads, which is pretty straightforward to do.
x = "xx yy 11 22 33"
gsub(" ", "", x)
> [1] "xxyy112233"
This is what jQuery API Doc says about .offset()
:
Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
This is what MDN Web API says about .offsetTop
:
offsetTop returns the distance of the current element relative to the top of the offsetParent node
This is what jQuery v.1.11 .offset()
basically do when getting the coords:
var box = { top: 0, left: 0 };
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
pageYOffset
intuitively says how much was the page scrolleddocElem.scrollTop
is the fallback for IE<9 (which are BTW unsupported in jQuery 2)docElem.clientTop
is the width of the top border of an element (the document in this case)elem.getBoundingClientRect()
gets the coords relative to the Conclusion
element.offsetTop
. Add element.scrollTop
if you want to take the parent scrolling into account. (or use jQuery .position() if you are fan of that library)element.getBoundingClientRect().top
. Add window.pageYOffset
if you want to take the document scrolling into account. You don't need to subtract document's clientTop
if the document has no border (usually it doesn't), so you have position relative to the documentelement.clientTop
if you don't consider the element border as the part of the elementSounds like you need to change the path to your java
executable to match the newest version.
Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.
Don't use quotes with <<EOF
:
var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF
Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).
In vue-cli version 3:
There are the three options for .env files:
Either you can use .env
or:
.env.test
.env.development
.env.production
You can use custom .env
variables by using the prefix regex as /^/
instead of /^VUE_APP_/
in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE
This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env
files. Because every time you npm install ..
, it will be overridden.
I've made this into an Xcode 4 template, in the same vein as Karl's static framework template.
I found that building static frameworks (instead of plain static libraries) was causing random crashes with LLVM, due to an apparent linker bug - so, I guess static libraries are still useful!
insert into tbl2
select field1,field2,... from tbl1
where not exists
(
select field1,field2,...
from person2
where (tbl1.field1=tbl2.field1 and
tbl1.field2=tbl2.field2 and .....)
)
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
Ids is the array of object ids:
const ids = [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e',
];
Using Mongoose with callback:
Model.find().where('_id').in(ids).exec((err, records) => {});
Using Mongoose with async function:
const records = await Model.find().where('_id').in(ids).exec();
Or more concise:
const records = await Model.find({ '_id': { $in: ids } });
Don't forget to change Model with your actual model.
My solution: open app on Android studio.
Check sdk
and clean App, after rebuild I had fixed this problem by following suggestions of Android Studio.
finally run app with react-native run-android/ios
Here's my take on this:
if(object_id(N'[dbo].[fn_Nth_Pos]', N'FN')) is not null
drop function [dbo].[fn_Nth_Pos];
GO
CREATE FUNCTION [dbo].[fn_Nth_Pos]
(
@find char, --char to find
@search varchar(max), --string to process
@nth int --occurrence
)
RETURNS int
AS
BEGIN
declare @pos int --position of nth occurrence
--init
set @pos = 0
while(@nth > 0)
begin
set @pos = charindex(@find,@search,@pos+1)
set @nth = @nth - 1
end
return @pos
END
GO
--EXAMPLE
declare @files table(name varchar(max));
insert into @files(name) values('abc_1_2_3_4.gif');
insert into @files(name) values('zzz_12_3_3_45.gif');
select
f.name,
dbo.fn_Nth_Pos('_', f.name, 1) as [1st],
dbo.fn_Nth_Pos('_', f.name, 2) as [2nd],
dbo.fn_Nth_Pos('_', f.name, 3) as [3rd],
dbo.fn_Nth_Pos('_', f.name, 4) as [4th]
from
@files f;
A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.
Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.
git reset <hash> # you need to know the last good hash, so you can remove all your local commits
git fetch upstream
git checkout master
git merge upstream/master
git push origin master -f
voila, now your fork is back to same as upstream.
join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
I had this exact problem and I solved it this way:
library(openxlsx) # loads library and doesn't require Java installed
your_df_list <- c("df1", "df2", ..., "dfn")
for(name in your_df_list){
write.xlsx(x = get(name),
file = "your_spreadsheet_name.xlsx",
sheetName = name)
}
That way you won't have to create a very long list manually if you have tons of dataframes to write to Excel.
In addition to CMS´ answer you may want to consider putting the style in an external stylesheet and assign the style to the id, like this:
#divCheckbox {
display: none;
}
You can do this simply like this
$('#image_id').click(function() {
$("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1');
});
where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.
A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:
# Search for entry.
for x in y:
if x == 3:
found = x
# Work with found entry.
try:
print('Found: {0}'.format(found))
except NameError:
print('Not found')
else:
# Handle rest of Found case here
...
You can do something like this.
<div>
{ object.map((item, index) => this.getComponent(item, index)) }
</div>
getComponent(item, index) {
switch (item.type) {
case '1':
return <Comp1/>
case '2':
return <Comp2/>
case '3':
return <Comp3 />
}
}
Go to
Settings -> Preferences -> Backup/Autocompletion
Check Enable auto-completion on each input. By default the radio button for Function completion gets checked, that will complete related function name as you type. But when you are editing something other than code, you can check for Word completion.
Check Function parameters hint on input, if you find it difficult to remember function parameters and their ordering.
In attribute inspector give the identifier for that view controller and the below code works for me
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
[self.navigationController pushViewController:detailViewController animated:YES];
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
An old post, but I love to share as I have the same case but I finally knew the problem :
Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.
Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.
But please inspect this sample that did not heed the above case :
<div class="btn-list" id="selected-country"></div>
Dynamically appended :
<button class="btn-map" data-country="'+country+'">'+ country+' </button>
This function is working good by clicking the button :
$(document).ready(function() {
$('#selected-country').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
})
or you can use body like :
$('body').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
compare to this that not working :
$(document).ready(function() {
$('.btn-map').on("click", function() {
var datacountry = $(this).data('country'); alert(datacountry);
});
});
hope it will help
I looked into this as well, and after comparing the SqlDataAdapter.Fill method with the SqlDataReader.Load funcitons, I've found that the SqlDataAdapter.Fill method is more than twice as fast with the result sets I've been using
Used code:
[TestMethod]
public void SQLCommandVsAddaptor()
{
long AdapterFillLargeTableTime, readerLoadLargeTableTime, AdapterFillMediumTableTime, readerLoadMediumTableTime, AdapterFillSmallTableTime, readerLoadSmallTableTime, AdapterFillTinyTableTime, readerLoadTinyTableTime;
string LargeTableToFill = "select top 10000 * from FooBar";
string MediumTableToFill = "select top 1000 * from FooBar";
string SmallTableToFill = "select top 100 * from FooBar";
string TinyTableToFill = "select top 10 * from FooBar";
using (SqlConnection sconn = new SqlConnection("Data Source=.;initial catalog=Foo;persist security info=True; user id=bar;password=foobar;"))
{
// large data set measurements
AdapterFillLargeTableTime = MeasureExecutionTimeMethod(sconn, LargeTableToFill, ExecuteDataAdapterFillStep);
readerLoadLargeTableTime = MeasureExecutionTimeMethod(sconn, LargeTableToFill, ExecuteSqlReaderLoadStep);
// medium data set measurements
AdapterFillMediumTableTime = MeasureExecutionTimeMethod(sconn, MediumTableToFill, ExecuteDataAdapterFillStep);
readerLoadMediumTableTime = MeasureExecutionTimeMethod(sconn, MediumTableToFill, ExecuteSqlReaderLoadStep);
// small data set measurements
AdapterFillSmallTableTime = MeasureExecutionTimeMethod(sconn, SmallTableToFill, ExecuteDataAdapterFillStep);
readerLoadSmallTableTime = MeasureExecutionTimeMethod(sconn, SmallTableToFill, ExecuteSqlReaderLoadStep);
// tiny data set measurements
AdapterFillTinyTableTime = MeasureExecutionTimeMethod(sconn, TinyTableToFill, ExecuteDataAdapterFillStep);
readerLoadTinyTableTime = MeasureExecutionTimeMethod(sconn, TinyTableToFill, ExecuteSqlReaderLoadStep);
}
using (StreamWriter writer = new StreamWriter("result_sql_compare.txt"))
{
writer.WriteLine("10000 rows");
writer.WriteLine("Sql Data Adapter 100 times table fill speed 10000 rows: {0} milliseconds", AdapterFillLargeTableTime);
writer.WriteLine("Sql Data Reader 100 times table load speed 10000 rows: {0} milliseconds", readerLoadLargeTableTime);
writer.WriteLine("1000 rows");
writer.WriteLine("Sql Data Adapter 100 times table fill speed 1000 rows: {0} milliseconds", AdapterFillMediumTableTime);
writer.WriteLine("Sql Data Reader 100 times table load speed 1000 rows: {0} milliseconds", readerLoadMediumTableTime);
writer.WriteLine("100 rows");
writer.WriteLine("Sql Data Adapter 100 times table fill speed 100 rows: {0} milliseconds", AdapterFillSmallTableTime);
writer.WriteLine("Sql Data Reader 100 times table load speed 100 rows: {0} milliseconds", readerLoadSmallTableTime);
writer.WriteLine("10 rows");
writer.WriteLine("Sql Data Adapter 100 times table fill speed 10 rows: {0} milliseconds", AdapterFillTinyTableTime);
writer.WriteLine("Sql Data Reader 100 times table load speed 10 rows: {0} milliseconds", readerLoadTinyTableTime);
}
Process.Start("result_sql_compare.txt");
}
private long MeasureExecutionTimeMethod(SqlConnection conn, string query, Action<SqlConnection, string> Method)
{
long time; // know C#
// execute single read step outside measurement time, to warm up cache or whatever
Method(conn, query);
// start timing
time = Environment.TickCount;
for (int i = 0; i < 100; i++)
{
Method(conn, query);
}
// return time in milliseconds
return Environment.TickCount - time;
}
private void ExecuteDataAdapterFillStep(SqlConnection conn, string query)
{
DataTable tab = new DataTable();
conn.Open();
using (SqlDataAdapter comm = new SqlDataAdapter(query, conn))
{
// Adapter fill table function
comm.Fill(tab);
}
conn.Close();
}
private void ExecuteSqlReaderLoadStep(SqlConnection conn, string query)
{
DataTable tab = new DataTable();
conn.Open();
using (SqlCommand comm = new SqlCommand(query, conn))
{
using (SqlDataReader reader = comm.ExecuteReader())
{
// IDataReader Load function
tab.Load(reader);
}
}
conn.Close();
}
Results:
10000 rows:
Sql Data Adapter 100 times table fill speed 10000 rows: 11782 milliseconds
Sql Data Reader 100 times table load speed 10000 rows: 26047 milliseconds
1000 rows:
Sql Data Adapter 100 times table fill speed 1000 rows: 984 milliseconds
Sql Data Reader 100 times table load speed 1000 rows: 2031 milliseconds
100 rows:
Sql Data Adapter 100 times table fill speed 100 rows: 125 milliseconds
Sql Data Reader 100 times table load speed 100 rows: 235 milliseconds
10 rows:
Sql Data Adapter 100 times table fill speed 10 rows: 32 milliseconds
Sql Data Reader 100 times table load speed 10 rows: 93 milliseconds
For performance issues, using the SqlDataAdapter.Fill method is far more efficient. So unless you want to shoot yourself in the foot use that. It works faster for small and large data sets.
Yes! In your settings.py define the following
LOGIN_REDIRECT_URL = '/your-path'
And have '/your-path' be a simple View that looks up self.request.user
and does whatever logic it needs to return a HttpResponseRedirect
object.
A better way might be to define a simple URL like '/simple'
that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.
I found it very useful to encode my URL to a safe one when I was returning a value through Ajax/PHP to a URL which was then read by the page again.
PHP output with URL encoder for the special character &
:
// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";
// JavaScript sending the value to the URL
window.location.href = 'time.php?return=updated&val=' + msg;
// JavaScript/PHP executing the function printing the value of the URL,
// now with the text normally lost in space because of the reserved & character.
setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');", 360);
Ternary operator works because the first part of it returns a Boolean value. In your case, jQuery's css method returns the jQuery object, thus not valid for ternary operation.
It's not a clever choice to move all .git*
by hand, particularly when these .git
files are hidden in sub-folders just like my condition: when I installed Skeleton Zend 2 by composer+git, there are quite a number of .git
files created in folders and sub-folders.
I tried rm -rf .git
on my GitHub shell, but the shell can not recognize the parameter -rf
of Remove-Item.
www.montanaflynn.me introduces the following shell command to remove all .git
files one time, recursively! It's really working!
find . | grep "\.git/" | xargs rm -rf
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
If still you are facing checkout for proxy setting, for me it was the proxy setting which were missing and was not able to make the request as direct http/https are blocked. So i configured the proxy from my organization while making the request.
npm install https-proxy-agent
or
npm install http-proxy-agent
const httpsProxyAgent = require('https-proxy-agent');
const agent = new httpsProxyAgent("http://yourorganzation.proxy.url:8080");
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
agent: agent
};
I would use a negative lookahead for any character:
^(?![\s\S])
This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.
For users of GitHub, this worked for me:
git reset --hard <full_hash_of_commit_to_reset_to>
git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset
command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.
You can design a lowpass Butterworth filter in runtime, using butter()
function, and then apply that to the signal.
fc = 300; % Cut off frequency
fs = 1000; % Sampling rate
[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal
Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html
Do you have the button specified as an IBOutlet in your view controller class, and is it connected properly as an outlet in Interface Builder (ctrl drag from new referencing outlet to file owner and select your UIButton object)? That's usually the problem I have when I see these symptoms.
Edit: While it's not the case here, something like this can also happen if you set an attributed title to the button, then you try to change the title and not the attributed title.
This works 100%
window.open('http://www.google.com/','_newtab' + Date.now());
View: View is just a named query. It doesn't store anything. When there is a query on view, it runs the query of the view definition. Actual data comes from table.
Materialised views: Stores data physically and get updated periodically. While querying MV, it gives data from MV.
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
More information can be found at Google Maps API - LatLng
Alternatively instead of turning 'no-console' off, you can allow. In the .eslintrc.js file put
rules: {
"no-console": [
"warn",
{ "allow": ["clear", "info", "error", "dir", "trace", "log"] }
]
}
This will allow you to do console.log
and console.clear
etc without throwing errors.
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
In Access 2013 I've just tested this:
While ComboBox1.ListCount > 0
ComboBox1.RemoveItem 0
Wend
Interestingly, if you set the item list in Properties, this is not lost when you exit Form View and go back to Design View.
In the new rspec
expect
syntax this would be:
expect(subject).to receive(:bar).with("an argument I want")
I had the same issue, the easiest way i found to insert the current date into a prepared statement is this one:
preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
To remove all non-ASCII characters, you can use following replacement: [^\x00-\x7F]+
To highlight characters, I recommend using the Mark function in the search window: this highlights non-ASCII characters and put a bookmark in the lines containing one of them
If you want to highlight and put a bookmark on the ASCII characters instead, you can use the regex [\x00-\x7F]
to do so.
Cheers
Interval class I have written can be used. It can be used in opposite way too.
composer require lubos/cakephp-interval
$Interval = new \Interval\Interval\Interval();
// output 2w 6h
echo $Interval->toHuman((2 * 5 * 8 + 6) * 3600);
// output 36000
echo $Interval->toSeconds('1d 2h');
More info here https://github.com/LubosRemplik/CakePHP-Interval
I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:
input[type=number] {
&,
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: textfield;
appearance: none;
&:hover,
&:focus {
-moz-appearance: number-input;
}
}
}
Tested on chrome, firefox, safari
The reason your functor example does not work is that you need an instance to invoke the operator()
.
There's also PyGTK, which is basically a Python wrapper for the Gnome Toolkit. I've found it easier to wrap my mind around than Tkinter, coming from pretty much no knowledge of GUI programming previously. It works pretty well and has some good tutorials. Unfortunately there isn't an installer for Python 2.6 for Windows yet, and may not be for a while.
Possible reason: The reason can be that this image is currently used by a running container. In such case, you can list running containers, stop the relevant container and then remove the image:
docker ps
docker stop <containerid>
docker rm <containerid>
docker rmi <imageid>
If you cannnot find container by docker ps, you can use this to list all already exited containers and remove them.
docker ps -a | grep 60afe4036d97
docker rm <containerid>
Note: Be careful of deleting all exited containers at once in case you use Volume-Only
containers. These stay in Exit
state, but contains useful data.
I had the same issue on my fresh Ubuntu 64 bit installation, and the path was set up correctly.
Thus, which adb
would resolve correctly, but trying to run it would fail with adb: command not found
.
The very helpful guys at #android-dev pointed me to the solution, namely that the 32 bit libraries hadn't been installed. On my previous computers, this had probably been pulled in as a dependency for another package.
On Ubuntu (probably other Debians as well), running [sudo] apt-get install ia32-libs
If the "core problem" is assigning class variables using functions, an alternative is to use a metaclass (it's kind of "annoying" and "magical" and I agree that the static method should be callable inside the class, but unfortunately it isn't). This way, we can refactor the behavior into a standalone function and don't clutter the class.
class KlassMetaClass(type(object)):
@staticmethod
def _stat_func():
return 42
def __new__(cls, clsname, bases, attrs):
# Call the __new__ method from the Object metaclass
super_new = super().__new__(cls, clsname, bases, attrs)
# Modify class variable "_ANS"
super_new._ANS = cls._stat_func()
return super_new
class Klass(object, metaclass=KlassMetaClass):
"""
Class that will have class variables set pseudo-dynamically by the metaclass
"""
pass
print(Klass._ANS) # prints 42
Using this alternative "in the real world" may be problematic. I had to use it to override class variables in Django classes, but in other circumstances maybe it's better to go with one of the alternatives from the other answers.
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.
Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.
Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.
In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.
I would suggest using Document Wrapped as the web service type of choice due to its advantages.
SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.
If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.
A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services
I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)
Fiddle: https://jsfiddle.net/tqmfpwhv/1/
css based on OP information, media query at end is for med & lg view.
.vr-all {
padding:0px;
border-right:1px solid #CC0000;
}
.vr-xs {
padding:0px;
}
.vr-md {
padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
border-color: #CC0000;
border-style: solid;
border-bottom: 1px;
margin:0px;
padding:0px;
}
/* for medium and up */
@media(min-width:992px){
.vr-xs {
border-right:1px solid #CC0000;
}
}
html adjustments to OP provided code. Red border and Img links for example.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
<h5>Rich Media Ad Production</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
<h5>Web Design & Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
<h5>Creative Design</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for for all viewports -->
<div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
<h5>Web Analytics</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
<h5>Search Engine Marketing</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
<h5>Quality Assurance</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
</div>
</div>
You can drop index duplicates with 'drop_duplicates':
df.loc[df.index.drop_duplicates(keep='first')]
This works for me to override all local changes and does not require an identity:
git reset --hard
git pull
There are also these 'ways':
>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}
I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.
If yes, then this is what you want to read.
And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)
Applying the full_extent()
function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()
which gives a little tighter bounding box
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox
def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + pad, 1.0 + pad)
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
I'd post a pic but I lack the reputation points
The idea of a foreign key is based on the concept of referencing a value that already exists in the main table. That is why it is called a foreign key in the other table. This concept is called referential integrity. If a foreign key is declared as a null field it will violate the the very logic of referential integrity. What will it refer to? It can only refer to something that is present in the main table. Hence, I think it would be wrong to declare a foreign key field as null.
Go to this link here https://drive.google.com/file/d/0B9mUXEcOsbhfdFR1ZnVKNWtXQlU/view Cuodos To https://www.reddit.com/r/iOSProgramming/comments/6fmtj1/is_it_possible_to_download_xcode_9_beta_without_a/dikyeh4/
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
That's because you missed ELSE.
"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)
For reference I want to add about ExtJS, as explained in Manual: RESTful Web Services. In short, use method to specify GET, POST, PUT, DELETE. Example:
Ext.Ajax.request({
url: '/articles/restful-web-services',
method: 'PUT',
params: {
author: 'Patrick Donelan',
subject: 'RESTful Web Services are easy with Ext!'
}
});
If the Accept header is necessary, it can be set as a default for all requests:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json'
};
Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.
Items of a ListBox
control may be DataRowView
, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember
.
ListBox
control has a GetItemText
which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue
method.
GetItemValue Extension Method
We can create GetItemValue
Extension Method to get item value which works like GetItemText
:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox
and it will return expected Value
for an item. It works with List<T>
, Array
, ArrayList
, DataTable
, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);
Since we created the GetItemValue
method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.
This method is applicable on ComboBox
and CheckedListBox
too.
ASCII representation:
[Source Code] ---> Compiler ---> [Object code] --*
|
[Source Code] ---> Compiler ---> [Object code] --*--> Linker --> [Executable] ---> Loader
| |
[Source Code] ---> Compiler ---> [Object code] --* |
| |
[Library file]--* V
[Running Executable in Memory]
The jsonify()
function in flask returns a flask.Response()
object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps()
method will just return an encoded string, which would require manually adding the MIME type header.
See more about the jsonify()
function here for full reference.
Edit:
Also, I've noticed that jsonify()
handles kwargs or dictionaries, while json.dumps()
additionally supports lists and others.
For primitive array types, you would have to write a reverse sort algorithm:
Alternatively, you can convert your int[]
to Integer[]
and write a comparator:
public class IntegerComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
or use Collections.reverseOrder()
since it only works on non-primitive array types.
and finally,
Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());
//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);
import static org.springframework.util.StringUtils.capitalize;
...
return capitalize(name);
NOTE: If you already have Apache Common Lang dependency, then consider using their StringUtils.capitalize as other answers suggest.
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
Here is my code based off the code offered by @Ahmed ALaa
Features:
*
character (DEC: 42 ; HEX: 0x2A)
instead of the input characterDemerits:
The function secure_password_input()
returns the password as a string
when called. It accepts a Password Prompt string, which will be displayed to the user to type the password
def secure_password_input(prompt=''):
p_s = ''
proxy_string = [' '] * 64
while True:
sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
c = msvcrt.getch()
if c == b'\r':
break
elif c == b'\x08':
p_s = p_s[:-1]
proxy_string[len(p_s)] = " "
else:
proxy_string[len(p_s)] = "*"
p_s += c.decode()
sys.stdout.write('\n')
return p_s
Just in case you can't / don't use CURLOPT_HEADERFUNCTION
or other solutions;
$nextCheck = function($body) {
return ($body && strpos($body, 'HTTP/') === 0);
};
[$headers, $body] = explode("\r\n\r\n", $result, 2);
if ($nextCheck($body)) {
do {
[$headers, $body] = explode("\r\n\r\n", $body, 2);
} while ($nextCheck($body));
}
Considering @Ben answer, R would throw an error if df1
does not contain x
column. But it can be solved elegantly with paste
:
aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)
Similarly, it can be generalized if more than two variables are used in grouping:
aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)
Why don't you take a look to this answer
Including javascript files inside javascript files
In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.
If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.
# -*- coding: UTF-8 -*-
This will fix some Unicode problems and make your life easier.
Mine is using LOCATE
in mysql:
LOCATE(substr,str), LOCATE(substr,str,pos)
This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.
In your case:
mysql_query("
SELECT * FROM `table`
WHERE LOCATE('{$needle}','column') > 0
");
The timer has special functions.
if you use StartAsync ()
or Start ()
, the thread does not block the user interface element
namespace UITimer
{
using thread = System.Threading;
public class Timer
{
public event Action<thread::SynchronizationContext> TaskAsyncTick;
public event Action Tick;
public event Action AsyncTick;
public int Interval { get; set; } = 1;
private bool canceled = false;
private bool canceling = false;
public async void Start()
{
while(true)
{
if (!canceled)
{
if (!canceling)
{
await Task.Delay(Interval);
Tick.Invoke();
}
}
else
{
canceled = false;
break;
}
}
}
public void Resume()
{
canceling = false;
}
public void Cancel()
{
canceling = true;
}
public async void StartAsyncTask(thread::SynchronizationContext
context)
{
while (true)
{
if (!canceled)
{
if (!canceling)
{
await Task.Delay(Interval).ConfigureAwait(false);
TaskAsyncTick.Invoke(context);
}
}
else
{
canceled = false;
break;
}
}
}
public void StartAsync()
{
thread::ThreadPool.QueueUserWorkItem((x) =>
{
while (true)
{
if (!canceled)
{
if (!canceling)
{
thread::Thread.Sleep(Interval);
Application.Current.Dispatcher.Invoke(AsyncTick);
}
}
else
{
canceled = false;
break;
}
}
});
}
public void StartAsync(thread::SynchronizationContext context)
{
thread::ThreadPool.QueueUserWorkItem((x) =>
{
while(true)
{
if (!canceled)
{
if (!canceling)
{
thread::Thread.Sleep(Interval);
context.Post((xfail) => { AsyncTick.Invoke(); }, null);
}
}
else
{
canceled = false;
break;
}
}
});
}
public void Abort()
{
canceled = true;
}
}
}
As a simple approximation you could use
grep -A100000 TERMINATE file
which greps for TERMINATE
and outputs up to 100000 lines following that line.
From man page
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.
In windows the default is: C:\Program Files\Java\jdk1.6.0_14
(where the numbers may differ, as they're the version).
If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data
and you have some function find_definition()
which gets the definition, you can do something like the following:
for word in data:
data[word] = find_definition(word)
I faced the same issues. To solve this, I used export PYTHONPATH="$PWD"
. However, in this case, you will need to modify imports in your Scripts
dir depending on the below:
Case 1: If you are in the user_management
dir, your scripts
should use this style from Modules import LDAPManager
to import module.
Case 2: If you are out of the user_management
1 level like main
, your scripts
should use this style from user_management.Modules import LDAPManager
to import modules.
This is a self-promotional answer, but I spent a few months researching this and presented the results at jQuery Conference San Francisco 2012.
Here is a free video of the talk:
You can do this with this library. https://github.com/itmor/events-js
const events = new Events();
events.add({
blockIsHidden: () => {
if ($('div').css('display') === 'none') return true;
}
});
function printText () {
console.log('The block has become hidden!');
}
events.on('blockIsHidden', printText);
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
s[0:"s".index("&")]
what does this do:
C:\wamp\bin\php\php5.3.13
Browse to the line that reads:
;extension=php_openssl.dll
and remove the semicolon preceding the line. Restart your WAMP server services (click in your icon tray > 'Restart All Services'
In practice, the models are used as follows.
In discriminative models, to predict the label y
from the training example x
, you must evaluate:
which merely chooses what is the most likely class y
considering x
. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.
Now, using Bayes' rule, let's replace the in the equation by . Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y
. So, you are left with
which is the equation you use in generative models.
While in the first case you had the conditional probability distribution p(y|x)
, which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y)
, since p(x | y) p(y) = p(x, y)
, which explicitly models the actual distribution of each class.
With the joint probability distribution function, given a y
, you can calculate ("generate") its respective x
. For this reason, they are called "generative" models.
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Add this in your css file:
.custom_class
{
background-image: url(../img/beach.jpg);
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
and then, in your .html (or .php) file call this class like that:
<div class="custom_class">
...
</div>
The simplest solution that I can think of is using Properties class.
Saving the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream("data.properties"), null);
Loading the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));
for (String key : properties.stringPropertyNames()) {
ldapContent.put(key, properties.get(key).toString());
}
EDIT:
if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
EDIT2:
instead of for loop (as suggested by OldCurmudgeon) in saving example:
properties.putAll(ldapContent);
however, for the loading example this is the best that can be done:
ldapContent = new HashMap<Object, Object>(properties);
You need to implement the equals() method in your MyClass
.
The reason that ==
didn't work is this is checking that they refer to the same instance. Since you did new
for each, each one is a different instance.
The reason that equals()
didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==
.
Note that you should also implement hashcode()
if you're going to implement equals()
because a lot of java.util Collections expect that.
This works on the latest version:
Use this method:
public static Intent getOpenFacebookIntent(Context context) {
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/<user_name_here>"));
}
}
This will open the Facebook app if the user has it installed. Otherwise, it will open Facebook in the browser.
EDIT: since version 11.0.0.11.23 (3002850) Facebook App do not support this way anymore, there's another way, check the response below from Jared Rummler.
Actually there are 3 places where gradle.properties
can be placed:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradlemyProject2
in your case)myProject
)Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
You can use:
(instancetype)init {
return [[YourSubclassOfTableView alloc] initWithStyle:UITableViewStyleGrouped];
}
The accepted answer is perfect, except it does not record outgoing calls. Note that for outgoing calls it is not possible (as near as I can tell from scouring many posts) to detect when the call is actually answered (if anybody can find a way other than scouring notifications or logs please let me know). The easiest solution is to just start recording straight away when the outgoing call is placed and stop recording when IDLE is detected. Just adding the same class as above with outgoing recording in this manner for completeness:
private void startRecord(String seed) {
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record" + seed;
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
startRecord("incoming");
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
startRecord("outgoing");
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state != null) {
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
}
}
}
}
On Python 3 numpy.genfromtxt
expects a bytes stream. Use the following:
numpy.genfromtxt(io.BytesIO(x.encode()))
Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.
unsigned short crc16(const unsigned char* data_p, unsigned char length){
unsigned char x;
unsigned short crc = 0xFFFF;
while (length--){
x = crc >> 8 ^ *data_p++;
x ^= x>>4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
}
return crc;
}
There's also this if you prefer:
mysql_query('SHOW COLUMNS FROM tableName');
From answer that was removed due to being written in Spanish:
All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.
Use
xmlns: compat = "http://schemas.android.com/tools"
on the menu label instead of
xmlns: compat = "http://schemas.android.com/apk/res-auto"
I did a little research and was able to write this code:
strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today. All assigned firms are complete. Please feel free to respond with any questions.<p>Thank you.</BODY>"
apparently by setting the "font-size=11pt"
instead of setting the font size <font size=5>
,
It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.
This link from simpLE MAn gave me some good info.
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
One method I did with mine, is to "Add to Source Control", and select 'Git'.
Share : Text
@IBAction func shareOnlyText(_ sender: UIButton) {
let text = "This is the text....."
let textShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
}
Share : Image
@IBAction func shareOnlyImage(_ sender: UIButton) {
let image = UIImage(named: "Product")
let imageShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Share : Text - Image - URL
@IBAction func shareAll(_ sender: UIButton) {
let text = "This is the text...."
let image = UIImage(named: "Product")
let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
let shareAll= [text , image! , myWebsite]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
You can also use array_reduce()
if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)
Or you could just perform a trim()
on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare()
or equals()
implementation).
Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs
Just simple use
=Format(today(), "dd/MM/yyyy")
will solve your problem.
I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824
We can use __call__
method to use other class methods as static methods.
class _Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
class Model:
def get_instance(conn, table_name):
""" do something"""
get_instance = _Callable(get_instance)
provs_fac = Model.get_instance(connection, "users")
EDIT: updated code in order to reflect changes made to the way pipes work in more recent versions of RXJS. All operators (take in my example) are now wrapped into the pipe() operator.
I realize that this Question was quite a while ago and you surely have a proper solution by now, but for anyone looking for this I would suggest solving it with a Promise to keep the async pattern.
A more verbose version would be creating a new Promise:
function getValueFromObservable() {
return new Promise(resolve=>{
this.store.pipe(
take(1) //useful if you need the data once and don't want to manually cancel the subscription again
)
.subscribe(
(data:any) => {
console.log(data);
resolve(data);
})
})
}
On the receiving end you will then have "wait" for the promise to resolve with something like this:
getValueFromObservable()
.then((data:any)=>{
//... continue with anything depending on "data" after the Promise has resolved
})
A slimmer solution would be using RxJS' .toPromise() instead:
function getValueFromObservable() {
return this.store.pipe(take(1))
.toPromise()
}
The receiving side stays the same as above of course.
This is a "feature" of the M2E plugin that had been introduced a while ago. It's not directly related to the JBoss EAR plugin but also happens with most other Maven plugins.
If you have a plugin execution defined in your pom
(like the execution of maven-ear-plugin:generate-application-xml
), you also need to add additional config information for M2E that tells M2E what to do when the build is run in Eclipse, e.g. should the plugin execution be ignored or executed by M2E, should it be also done for incremental builds, ... If that information is missing, M2E complains about it by showing this error message:
"Plugin execution not covered by lifecycle configuration"
See here for a more detailed explanation and some sample config that needs to be added to the pom to make that error go away:
https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html
There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.
What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:
div {
position: absolute;
top: 300px;
bottom: 0px;
left: 30px;
right: 30px;
}
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto;
to handle cases where the content is larger than the div.
.modal.in .modal-dialog {
width:100% !important;
min-height: 100%;
margin: 0 0 0 0 !important;
bottom: 0px !important;
top: 0px;
}
.modal-content {
border:0px solid rgba(0,0,0,.2) !important;
border-radius: 0px !important;
-webkit-box-shadow: 0 0px 0px rgba(0,0,0,.5) !important;
box-shadow: 0 3px 9px rgba(0,0,0,.5) !important;
height: auto;
min-height: 100%;
}
.modal-dialog {
position: fixed !important;
margin:0px !important;
}
.bootstrap-dialog .modal-header {
border-top-left-radius: 0px !important;
border-top-right-radius: 0px !important;
}
@media (min-width: 768px)
.modal-dialog {
width: 100% !important;
margin: 0 !important;
}
This is the best .htaccess
I have used in my actual website:
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
##Tweaks##
Header set X-Frame-Options SAMEORIGIN
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_headers.c>
Header set Connection keep-alive
<filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
Header set Cache-Control "max-age=2592000, public"
</filesmatch>
<filesmatch "\.(jpg|jpeg|png)$">
Header set Cache-Control "max-age=1209600, public"
</filesmatch>
# css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
<filesmatch "\.(css)$">
Header set Cache-Control "max-age=31536000, private"
</filesmatch>
<filesmatch "\.(js)$">
Header set Cache-Control "max-age=1209600, private"
</filesmatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</filesMatch>
</IfModule>
Do you have a lot of applications running when you are trying this? I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000. It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
No need to promise with $http, i use it just with two returns :
myApp.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data;
}).error(function(){
alert("error");
return null ;
});
}
});
In controller
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
restarting the adb server as root worked for me. see:
derek@zoe:~/Downloads$ adb sideload angler-ota-mtc20f-5a1e93e9.zip
loading: 'angler-ota-mtc20f-5a1e93e9.zip'
error: insufficient permissions for device
derek@zoe:~/Downloads$ adb devices
List of devices attached
XXXXXXXXXXXXXXXX no permissions
derek@zoe:~/Downloads$ adb kill-server
derek@zoe:~/Downloads$ sudo adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
derek@zoe:~/Downloads$ adb devices
List of devices attached
XXXXXXXXXXXXXXXX sideload
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
Use the following snippet for Bootstrap 4, which extends jQuery:
(function( $ ) {
$.fn.hideShow = function( action ) {
if ( action.toUpperCase() === "SHOW") {
// show
if(this.hasClass("d-none"))
{
this.removeClass("d-none");
}
this.addClass("d-block");
}
if ( action.toUpperCase() === "HIDE" ) {
// hide
if(this.hasClass("d-block"))
{
this.removeClass("d-block");
}
this.addClass("d-none");
}
return this;
};
}( jQuery ));
Include the file after jQuery has been included.
Use it using the syntax
$().hideShow('hide');
$().hideShow('show');
hope you guys find it helpful. :-)
If you don't want to show the series names in the legend you can disable them by setting showInLegend:false
.
example:
series: [{
showInLegend: false,
name: "<b><?php echo $title; ?></b>",
data: [<?php echo $yaxis; ?>],
}]
You get other options here.
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
max
is a builtin function in python, which is used to get max value from a sequence, i.e (list, tuple, set, etc..)
print(max([9, 7, 12, 5]))
# prints 12
If you are a beginner, it is better you first go through some basic tutorials and after that learn about naming conventions. I have gone through the following to learn Angular, some of which are very effective.
Tutorials :
Details of application structure and naming conventions can be found in a variety of places. I've gone through 100's of sites and I think these are among the best:
From Save MySQL query results into a text or CSV file:
MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.
Given a query such as
SELECT order_id,product_name,qty FROM orders
which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:
SELECT order_id,product_name,qty FROM orders INTO OUTFILE '/tmp/orders.txt'
This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:
SELECT order_id,product_name,qty FROM orders INTO OUTFILE '/tmp/orders.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'
In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:
"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"
Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.
Syntax
SELECT Your_Column_Name
FROM Your_Table_Name
INTO OUTFILE 'Filename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Or you could try to grab the output via the client:
You could try executing the query from the your local client and redirect the output to a local file destination:
mysql -user -pass -e "select cols from table where cols not null" > /tmp/output
Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv'
or INTO OUTFILE './output.csv'
, it will store the output file to the directory specified by show variables like 'datadir';
.