_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d6901 | train | Have ng-click like this. Pass all the details necessary to navigate to your chosen state.
<td class="text-left">
<a class="curosr" ng-click="navigateToDetails(x)">{{x.name}}
</a>
</td>
And in controller, first inject $state as dependency, and then, use $state.go to navigate to the state.
$scope.navigateToDetails = function(x) {
// some amazing code to decide whether or not to navigate
$state.go("private.Registered_details", {
uid: x.userID,
vid: x.vehicleID,
page_value:'page1'
});
} | unknown | |
d6902 | train | A union is just going to decrease readability of your code. And depending on how you use it will increase maintenance too. Actually the fact that you mentioned "implementing the rule of 5" despite having a std::string member suggests that your class is going to be a nightmare to maintain.
I would look at these options (not enough detail in the question to determine what would be best):
*
*Use an exception. You can make a custom exception by deriving from std::exception
*Use Boost.Optional.
boost::optional<std::string> do_something() { ... };
std::string result = do_something().value_or("error!"); | unknown | |
d6903 | train | First define your tweet class:
public class Tweet {
public long StatusId { get; set; }
public string Author { get; set; }
public string Content { get; set; }
}
Then try this statement like this:
var newTweet = new Tweet { StatusId = 2344
, Author = "@AuthorName"
, Content = "this is a tweet" };
graphClient.Cypher
.Merge("(tweet:Tweet { StatusId: {id} })")
.OnCreate()
.Set("tweet = {newTweet}")
.WithParams(new {
id = newTweet.StatusId,
newTweet
})
.ExecuteWithoutResults(); | unknown | |
d6904 | train | You can use QueryOver, it's a wrapper on ICriteria with Lambda Expressions:
session.QueryOver<HobbyDetail>()
.Fetch(hobbyDetail => hobbyDetail.HobbyMasters).Eager
.TransformUsing(Transformers.DistinctRootEntity)
.List(); | unknown | |
d6905 | train | Try this:
#define RADIANS(degrees) ((degrees * M_PI) / 180.0)
CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5.0));
CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5.0));
for (UICollectionView *cell in self.gridView.visibleCells) {
cell.transform = leftWobble;
}
[UIView beginAnimations:@"wobble" context:nil];
[UIView setAnimationRepeatAutoreverses:YES]; // important
[UIView setAnimationRepeatCount:10];
[UIView setAnimationDuration:1.25];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(wobbleEnded:finished:context:)];
for (UICollectionViewCell *cell in self.gridView.visibleCells) {
cell.transform = rightWobble;
}
[UIView commitAnimations];
how can I add a small delete buttons inside the upper left of the collection view cells programmatically in this loop?
Add delete button as UIButton to your cell's subviews in you custom UICollectionViewCell subclass, and setHidden:NO when needed.
Also just found out, my entire view wobbles when I side scroll, not
just the cells.... Very odd.
Edited. | unknown | |
d6906 | train | Destructure id and spread the rest
course.map( ({ id, ...item }) => (
<div id={id}> {item.foo} </div>
))
A: You can't destruct an object into its an element and itself.
It could be better destruct item in the callback function like below.
console.log('-------Only get rest obj------');
const courses = [{ name: "Half Stack application development", id: 1 }, { name: "Node.js", id: 2 }];
courses.forEach(({id, ...item}) => console.log('rest obj:', item));
console.log('----Get full obj and destruct---------');
courses.forEach(item => {
const { id } = item;
console.log('id:', id);
console.log('item:', item);
});
A: return (
<div>
{course.map(item => {
return <Course key={item.id} course={item} />;
})}
</div>
);
You are trying to use the course variable again inside map function.
Rename outer most variable from course to courses.
return (
<div>
{courses.map(course => {
return <Course key={course.id} course={course} />;
})}
</div>
);
A: Consider below example
return (
<div>
{course.map(({ id, ...course }) => {
return <Course key={id} course={course} />;
})}
</div>
);
It does gets us the id but course object does have all the keys of the original object(ie, it doesn't have the id now). | unknown | |
d6907 | train | First read, Performing Custom Painting and Painting in AWT and Swing to get a better understanding how painting in Swing works and how you're suppose to work with it.
But I already have ...
public void paint(Graphics g){
drawMenu((Graphics2D)g);
}
would suggest otherwise. Seriously, go read those links so you understand all the issues that the above decision is going to create for you.
You're operating in a OO language, you need to take advantage of that and decouple your code and focus on the "single responsibility" principle.
I'm kind of tired of talking about it, so you can do some reading:
*
*https://softwareengineering.stackexchange.com/questions/244476/what-is-decoupling-and-what-development-areas-can-it-apply-to
*Cohesion and Decoupling, what do they represent?
*Single Responsibility Principle
*Single Responsibility Principle in Java with Examples
*SOLID Design Principles Explained: The Single Responsibility Principle
These are basic concepts you really need to understand as they will make your live SOOO much easier and can be applied to just about any language.
As an example, from your code...
public HomeMenu(GameFrame owner,Dimension area){
//...
this.setPreferredSize(area);
There is no good reason (other than laziness (IMHO)) that any caller should be telling a component what size it should be, that's not their responsibility. It's the responsibility of the component to tell the parent container how big it would like to be and for the parent component to figure out how it's going to achieve that (or ignore it as the case may be).
The "basic" problem you're having is a simple one. Your "God" class is simply trying to do too much (ie it's taken on too much responsibility). Now we "could" add a dozen or more flags into the code to compensate for this, which is just going to increase the coupling and complexity, making it harder to understand and maintain, or we can take a step back, break it down into individual areas of responsibility and build the solution around those, for example...
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new HomePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class HomePane extends JPanel {
public HomePane() {
setLayout(new BorderLayout());
navigateToMenu();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void navigateToMenu() {
removeAll();
HomeMenuPane pane = new HomeMenuPane(new HomeMenuPane.NavigationListener() {
@Override
public void navigateToInfo(HomeMenuPane source) {
HomePane.this.navigateToInfo();
}
@Override
public void navigateToStartGame(HomeMenuPane source) {
startGame();
}
});
add(pane);
revalidate();
repaint();
}
protected void navigateToInfo() {
removeAll();
HowToPlayPane pane = new HowToPlayPane(new HowToPlayPane.NavigationListener() {
@Override
public void navigateBack(HowToPlayPane source) {
navigateToMenu();
}
});
add(pane);
revalidate();
repaint();
}
protected void startGame() {
removeAll();
add(new JLabel("This is pretty awesome, isn't it!", JLabel.CENTER));
revalidate();
repaint();
}
}
public abstract class AbstractBaseMenuPane extends JPanel {
protected static final Color BORDER_COLOR = new Color(200, 8, 21); //Venetian Red
protected static final Color DASH_BORDER_COLOR = new Color(255, 216, 0);//school bus yellow
protected static final Color TEXT_COLOR = new Color(255, 255, 255);//white
protected static final Color CLICKED_BUTTON_COLOR = Color.ORANGE.darker();
protected static final Color CLICKED_TEXT = Color.ORANGE.darker();
protected static final int BORDER_SIZE = 5;
protected static final float[] DASHES = {12, 6};
private Rectangle border;
private BasicStroke borderStoke;
private BasicStroke borderStoke_noDashes;
private BufferedImage backgroundImage;
public AbstractBaseMenuPane() {
borderStoke = new BasicStroke(BORDER_SIZE, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, DASHES, 0);
borderStoke_noDashes = new BasicStroke(BORDER_SIZE, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
border = new Rectangle(new Point(0, 0), getPreferredSize());
// You are now responsible for filling the background
setOpaque(false);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
BufferedImage backgroundImage = getBackgroundImage();
if (backgroundImage != null) {
g2d.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
}
Color prev = g2d.getColor();
Stroke tmp = g2d.getStroke();
g2d.setStroke(borderStoke_noDashes);
g2d.setColor(DASH_BORDER_COLOR);
g2d.draw(border);
g2d.setStroke(borderStoke);
g2d.setColor(BORDER_COLOR);
g2d.draw(border);
g2d.dispose();
}
public void setBackgroundImage(BufferedImage backgroundImage) {
this.backgroundImage = backgroundImage;
repaint();
}
public BufferedImage getBackgroundImage() {
return backgroundImage;
}
}
public class HomeMenuPane extends AbstractBaseMenuPane {
public static interface NavigationListener {
public void navigateToInfo(HomeMenuPane source);
public void navigateToStartGame(HomeMenuPane source);
}
private static final String GAME_TITLE = "BRICK DESTROY";
private static final String START_TEXT = "START";
private static final String INFO_TEXT = "INFO";
private Rectangle startButton;
private Rectangle infoButton;
private Font gameTitleFont;
private Font buttonFont;
// Don't do this, this just sucks (for so many reasons)
// Use ImageIO.read instead and save yourself a load of frustration
//private Image img = Toolkit.getDefaultToolkit().createImage("1.jpeg");
private Point lastClickPoint;
private NavigationListener navigationListener;
public HomeMenuPane(NavigationListener navigationListener) {
this.navigationListener = navigationListener;
try {
setBackgroundImage(ImageIO.read(getClass().getResource("/images/BrickWall.jpg")));
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
lastClickPoint = p;
if (startButton.contains(p)) {
peformStartGameAction();
} else if (infoButton.contains(p)) {
performInfoAction();
}
repaint();
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
lastClickPoint = null;
repaint();
}
});
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if (startButton.contains(p) || infoButton.contains(p)) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
});
Dimension area = getPreferredSize();
Dimension btnDim = new Dimension(area.width / 3, area.height / 12);
startButton = new Rectangle(btnDim);
infoButton = new Rectangle(btnDim);
gameTitleFont = new Font("Calibri", Font.BOLD, 28);
buttonFont = new Font("Calibri", Font.BOLD, startButton.height - 2);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Color prevColor = g2d.getColor();
Font prevFont = g2d.getFont();
//methods calls
drawText(g2d);
drawButton(g2d);
//end of methods calls
g2d.setFont(prevFont);
g2d.setColor(prevColor);
g2d.dispose();
}
private void drawText(Graphics2D g2d) {
g2d.setColor(TEXT_COLOR);
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D gameTitleRect = gameTitleFont.getStringBounds(GAME_TITLE, frc);
int sX, sY;
sY = (int) (getHeight() / 4);
sX = (int) (getWidth() - gameTitleRect.getWidth()) / 2;
sY += (int) gameTitleRect.getHeight() * 1.1;//add 10% of String height between the two strings
g2d.setFont(gameTitleFont);
g2d.drawString(GAME_TITLE, sX, sY);
}
private void drawButton(Graphics2D g2d) {
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D txtRect = buttonFont.getStringBounds(START_TEXT, frc);
Rectangle2D mTxtRect = buttonFont.getStringBounds(INFO_TEXT, frc);
g2d.setFont(buttonFont);
int x = (getWidth() - startButton.width) / 2;
int y = (int) ((getHeight() - startButton.height) * 0.5);
startButton.setLocation(x, y);
x = (int) (startButton.getWidth() - txtRect.getWidth()) / 2;
y = (int) (startButton.getHeight() - txtRect.getHeight()) / 2;
x += startButton.x;
y += startButton.y + (startButton.height * 0.9);
if (lastClickPoint != null && startButton.contains(lastClickPoint)) {
Color tmp = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(startButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(START_TEXT, x, y);
g2d.setColor(tmp);
} else {
g2d.draw(startButton);
g2d.drawString(START_TEXT, x, y);
}
x = startButton.x;
y = startButton.y;
y *= 1.3;
infoButton.setLocation(x, y);
x = (int) (infoButton.getWidth() - mTxtRect.getWidth()) / 2;
y = (int) (infoButton.getHeight() - mTxtRect.getHeight()) / 2;
x += infoButton.getX();
y += infoButton.getY() + (startButton.height * 0.9);
if (lastClickPoint != null && infoButton.contains(lastClickPoint)) {
Color tmp = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(infoButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(INFO_TEXT, x, y);
g2d.setColor(tmp);
} else {
g2d.draw(infoButton);
g2d.drawString(INFO_TEXT, x, y);
}
}
protected void peformStartGameAction() {
navigationListener.navigateToStartGame(this);
}
protected void performInfoAction() {
navigationListener.navigateToInfo(this);
}
}
public class HowToPlayPane extends AbstractBaseMenuPane {
public static interface NavigationListener {
public void navigateBack(HowToPlayPane source);
}
private static final String HOW_TO_PLAY_TEXT = """
1- Click Start\n
2- Choose the mode\n
3- Each mode has 3 levels\n
4- To play/pause press space, use 'A' and 'D' to move\n
5- To open pause menu press 'ESC'\n
6- To open DebugPanel press 'ALT-SHIFT-F1'""";
private static final String BACK_TEXT = "BACK";
private static final String INFO_TEXT = "INFO";
private Rectangle backButton;
private boolean backClicked = false;
private Font infoFont;
private Font howtoPlayFont;
private NavigationListener navigationListener;
public HowToPlayPane(NavigationListener navigationListener) {
this.navigationListener = navigationListener;
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if (backButton.contains(p)) {
backClicked = true;
repaint();
performBackAction();
}
}
@Override
public void mouseReleased(MouseEvent e) {
backClicked = false;
}
});
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent mouseEvent) {
Point p = mouseEvent.getPoint();
if (backButton.contains(p)) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
});
Dimension btnDim = new Dimension(getPreferredSize().width / 3, getPreferredSize().height / 12);
backButton = new Rectangle(btnDim);
infoFont = new Font("Calibri", Font.BOLD, 24);
howtoPlayFont = new Font("Calibri", Font.PLAIN, 14);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(BORDER_COLOR);
g2d.fillRect(0, 0, getWidth(), getHeight());
FontRenderContext frc = g2d.getFontRenderContext();
Rectangle2D infoRec = infoFont.getStringBounds(INFO_TEXT, frc);
//
// Color prev = g2d.getColor();
//
// Stroke tmp = g2d.getStroke();
//
// g2d.setStroke(borderStoke_noDashes);
// g2d.setColor(DASH_BORDER_COLOR);
// g2d.draw(infoFace);
//
// g2d.setStroke(borderStoke);
// g2d.setColor(BORDER_COLOR);
// g2d.draw(infoFace);
//
// g2d.fillRect(0, 0, infoFace.width, infoFace.height);
//
// g2d.setStroke(tmp);
//
// g2d.setColor(prev);
//
g2d.setColor(TEXT_COLOR);
int sX, sY;
sY = (int) (getHeight() / 15);
sX = (int) (getWidth() - infoRec.getWidth()) / 2;
sY += (int) infoRec.getHeight() * 1.1;//add 10% of String height between the two strings
g2d.setFont(infoFont);
g2d.drawString(INFO_TEXT, sX, sY);
TextLayout layout = new TextLayout(HOW_TO_PLAY_TEXT, howtoPlayFont, frc);
String[] outputs = HOW_TO_PLAY_TEXT.split("\n");
for (int i = 0; i < outputs.length; i++) {
g2d.setFont(howtoPlayFont);
g2d.drawString(outputs[i], 40, (int) (80 + i * layout.getBounds().getHeight() + 0.5));
}
backButton.setLocation(getWidth() / 3, getHeight() - 50);
int x = (int) (backButton.getWidth() - infoRec.getWidth()) / 2;
int y = (int) (backButton.getHeight() - infoRec.getHeight()) / 2;
x += backButton.x + 11;
y += backButton.y + (layout.getBounds().getHeight() * 1.35);
backButton.setLocation(getWidth() / 3, getHeight() - 50);
if (backClicked) {
Color tmp1 = g2d.getColor();
g2d.setColor(CLICKED_BUTTON_COLOR);
g2d.draw(backButton);
g2d.setColor(CLICKED_TEXT);
g2d.drawString(BACK_TEXT, x, y);
g2d.setColor(tmp1);
repaint();
} else {
g2d.draw(backButton);
g2d.drawString(BACK_TEXT, x, y);
}
g2d.dispose();
}
protected void performBackAction() {
navigationListener.navigateBack(this);
}
}
}
Now, this example makes use of components to present different views (it even has a nice abstract implementation to allow for code re-use ), but it occurs to me, that, if you "really" wanted to, you could have a series of "painter" classes, which could be used to delegate the painting of the current state to, and mouse clicks/movements could be delegated to, meaning you could have a single component, which would simple delegate the painting (via the paintComponent method) to which ever painter is active.
And, wouldn't you know it, they have a design principle for that to, the Delegation Pattern
The above example also makes use of the observer pattern, so you might want to have a look into that as well | unknown | |
d6908 | train | Your String solution is fine and in fact quite common. If you're interested in making it more compact, you may want to use a tuple of integers.
Another common method used in distributed systems is to use range allocation: have a central (singleton) server which allocates ranges in which each client can name its IDs. Such server could allocate, for example, the range 0-99 to client1, 100-199 to client2 etc. When a client exhausts the range it was allocated, it contacts the server again to allocate a new range.
A: Depending on the ranges of your stream/event numbers, you could combine the two numbers into a single int or long, placing the stream number in the top so many bits and the event number in the bottom so many bits. For example:
public static int getCombinedNo(int streamNo, int eventNo) {
if (streamNo >= (1 << 16))
throw new IllegalArgumentException("Stream no too big");
if (eventNo >= (1 << 16))
throw new IllegalArgumentException("Event no too big");
return (streamNo << 16) | eventNo;
}
This will only use 4 bytes per int as opposed to in the order of (say) 50-ish bytes for a typical String of the type you mention. (In this case, it also assumes that neither stream nor event number will exceed 65535.)
But: your string solution is also nice and clear. Is memory really that tight that you can't spare an extra 50 bytes per event? | unknown | |
d6909 | train | Is your question whether or not this is possible? Then the answer is "Yes!" -- What else would you like to know? Are there any details to your question? Specific areas you would like to concentrate on? Areas that are causing you problems? Or are you simply looking for a full solution? | unknown | |
d6910 | train | You need to use views keys query parameter to get records with keys in specified set.
function(doc){
emit(doc.table.id, null);
}
And then
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]
To retrieve document content in same time just add include_docs=True query parameter to your request.
UPD: Probably, you might be interested to retrieve documents by this reference ids (2,4,56). By default CouchDB views "maps" emitted keys with documents they belongs to. To tweak this behaviour you could use linked documents trick:
function(doc){
emit(doc.table.id, {'_id': doc.table.id});
}
And now request
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]&include_docs=True
will return rows with id field that points to document that holds 2,4 and 56 keys and doc one that contains referenced document content.
A: In CouchDB Bulk document APi is used for this:
curl -d '{"keys":["2","4", "56"]}' -X POST http://127.0.0.1:5984/foo/_all_docs?include_docs=true
http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API | unknown | |
d6911 | train | You need to call the addItemsOnSpinner2() function when the first spinner item has got selected.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
addItemsOnSpinner2();}
A: you are setting both spinner at the beginning of the code ( in onCreate). You should populate the second spinner after the spinner1 data is changed
A: yes as the gentlemen before me said.
In order for the second spinner to get the correct index to set the list,
you need to populate it after the first spinner is clicked.
/* wrong answer deleted */
if this is my code i would change addItemsOnSpinner2() into:
private void addItemsOnSpinner2(int selectedIndex){
int positionTop = selectedIndex;
//rest is the same
/* ... */
}
and again insert these into addItemsOnSpinner1():
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
if(arg2>0)
addItemsOnSpinner2(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
addItemsOnSpinner2(0);
}}
);
that is just how i would do it
i think many ways works here though
edit2:oh and edit the addItemsOnSpinner2() in onCreate() into addItemsOnSpinner2(0)
edit3:you need to call addItemsOnSpinner2() in onCreate(), otherwise your spinner is empty!
edit4:sorry guys, i made a huge mistake into thinking onItemClickListener could be applied here, shame on me :((
btw, if you want to keep the index (under situation like change of screen orientation or back to foreground ) , it needs more complicated work
but here is a much simpler method:
1.set a global static variable: int selectedIndex;
2.in onCreate, set selectedIndex to 0 if savedInstanceState is null
3.in onCreate, after savedInstanceState is nullcheckd, call addItemsOnSpinner2(selectedIndex)
4.in spinner1's listener, set selectedIndex to selected index.
not guarranteed to work on every machine though:( | unknown | |
d6912 | train | The DataGridView does not provide a SelectedDataRows and SelectedRows in not Linq-enabled, so Yes, you will have to write a foreach loop.
A: A generic extension method to add "SelectedDataRows" to DataGridViews:
public static T[] SelectedDataRows<T>(this DataGridView dg) where T : DataRow
{
T[] rows = new T[dg.SelectedRows.Count];
for (int i = 0; i < dg.SelectedRows.Count; i++)
rows[i] = (T)((DataRowView)dg.SelectedRows[i].DataBoundItem).Row;
return rows;
}
This is generic so that you can return a typed data row using Typed Datasets. You could make yours just return a DataRow[] if you wanted. This also assumes that your DataGridView has a DataView bound to it. | unknown | |
d6913 | train | getElementsByClassName returns a HTMLCollection. You must iterate it:
var elements = document.getElementsByClassName("hungry-menu-item-price");
for(var i=0; i<elements.length; ++i)
elements[i].textContent = elements[i].textContent.replace(".00", "");
<p class="hungry-menu-item-price">$24.00</p>
A: document.getElementsByClassName() function returns a nodeList, not an element
so it must be :
document.getElementsByClassName('hungry-menu-item-price')[0].innerHTML | unknown | |
d6914 | train | Automatic indenting kicked in.
The easiest way to disable it is: :set paste
:help paste
'paste' boolean (default off)
global
{not in Vi}
Put Vim in Paste mode. This is useful if you want to cut or copy
some text from one window and paste it in Vim. This will avoid
unexpected effects.
Setting this option is useful when using Vim in a terminal, where Vim
cannot distinguish between typed text and pasted text. In the GUI, Vim
knows about pasting and will mostly do the right thing without 'paste'
being set. The same is true for a terminal where Vim handles the
mouse clicks itself.
A: Karoly's answer is correct regarding the paste option.
You can then add a mapping in your .vimrc to quickly enable/disable 'paste' option:
For example, I use
set pastetoggle=<F10>
A: You can also let vim handle the situation automatically for you.
With the following in your ~\.vimrc
let &t_SI .= "\<Esc>[?2004h"
let &t_EI .= "\<Esc>[?2004l"
inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
function! XTermPasteBegin()
set pastetoggle=<Esc>[201~
set paste
return ""
endfunction
you can paste freely without worrying about the auto-indentions.
If you work in tmux, then you have to write instead the following
function! WrapForTmux(s)
if !exists('$TMUX')
return a:s
endif
let tmux_start = "\<Esc>Ptmux;"
let tmux_end = "\<Esc>\\"
return tmux_start . substitute(a:s, "\<Esc>", "\<Esc>\<Esc>", 'g') . tmux_end
endfunction
let &t_SI .= WrapForTmux("\<Esc>[?2004h")
let &t_EI .= WrapForTmux("\<Esc>[?2004l")
function! XTermPasteBegin()
set pastetoggle=<Esc>[201~
set paste
return ""
endfunction
inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
The source is Coderwall if you would like to read more. | unknown | |
d6915 | train | Regarding:
My question is why is DocuSign Connect not returning a signed PDF version of the docx file that was sent?
DocuSign did return a PDF document to you. Your conclusion that the file was not a PDF file is not correct.
The filename field is just informational, the file extension in the filename field is also not significant.
What is significant:
*
*DocuSign needs to know the file type of the input / uploaded files. It uses the fileExtension field to learn from the submittor what the filetype is.
*If the file type is anything other than pdf, it will always be converted to pdf. There are no exceptions.
*If the file type is pdf, the pdf file will be "flattened" (rasterized) to ensure that no malware within the pdf can harm a signer or other recipient. (PDF files are actually programs. The programs usually just produce a printed page, but they can do far more, both for good and for evil. But I digress.)
*If you choose to have the webhook system (Connect or eventNotifications) send you files, those files will always be in pdf format.
*The fileExtension field is referring to the file type that was sent to DocuSign. The correct file extension for a file downloaded from DocuSign is always .pdf.
In your case, I opened your "problematic" XML notification message and copied the PDFBytes content to an online base64 decoder. I then opened the output using a pdf viewer and was shown your signed document.
It doesn't matter what the "name" of the document is/was. Output from DocuSign is always in the form of a PDF document. | unknown | |
d6916 | train | Have you considered a database trigger? Below example is taken from this StackExhange post:
CREATE OR REPLACE FUNCTION check_number_of_row()
RETURNS TRIGGER AS
$body$
BEGIN
IF (SELECT count(*) FROM your_table) > 10
THEN
RAISE EXCEPTION 'INSERT statement exceeding maximum number of rows for this table'
END IF;
END;
$body$
LANGUAGE plpgsql;
CREATE TRIGGER tr_check_number_of_row
BEFORE INSERT ON your_table
FOR EACH ROW EXECUTE PROCEDURE check_number_of_row();
Unfortunately triggers don't seem to be supported in Prisma yet, so you will have to define it in SQL: https://github.com/prisma/prisma/discussions/2382
A: You can achieve it with interactive transaction, here's my example code:
const createPost = async (post, userId) => {
return prisma.$transaction(async (prisma) => {
// 1. Count current total user posts
const currentPostCount = await prisma.posts.count({
where: {
user_id: userId,
},
})
// 2. Check if user can create posts
if (currentPostCount >= 10) {
throw new Error(`User ${userId} has reached maximum posts}`)
}
// TODO
// 3. Create your posts here
await prisma.posts.create({
data: post
})
})
} | unknown | |
d6917 | train | You can get the CPU and memory usage of a process using ps. If you know the pid of the process, then a command like this will give you the percentage CPU usage and memory usage in kilobytes:
ps -o pcpu,rss -p <pid>
You can redirect the output of this to a file in the usual way, and do whatever you want with it. Other variables that you can get in this way can be found in man ps (or here), in the section on Standard Format Specifiers. | unknown | |
d6918 | train | The "advantage" of from xyz import * as opposed to other forms of import is that it imports everything (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module without prefixing them with the module's name. For example
>>> from math import *
>>>pi
3.141592653589793
>>>sin(pi/2)
>>>1.0
This practice (of importing * into the current namespace) is however discouraged because it
*
*provides the opportunity for namespace collisions (say if you had a variable name pi prior to the import)
*may be inefficient, if the number of objects imported is big
*doesn't explicitly document the origin of the variable/method/class (it is nice to have this "self documentation" of the program for future visit into the code)
Typically we therefore limit this import * practice to ad-hoc tests and the like. As pointed out by @Denilson-Sá-Maia, some libraries such as (e.g. pygame) have a sub-module where all the most commonly used constants and functions are defined and such sub-modules are effectively designed to be imported with import *. Other than with these special sub-modules, it is otherwise preferable to ...:
explicitly import a few objects only
>>>from math import pi
>>>pi
>>>3.141592653589793
>>> sin(pi/2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
or import the module under its own namespace (or an alias thereof, in particular if this is a long name, and the program references its objects many times)
>>>import math
>>>math.pi
>>>3.141592653589793
etc..
>>>import math as m #bad example math being so short and standard...
>>>m.pi
>>>3.141592653589793
etc..
See the Python documentation on this topic
(a) Specifically, what gets imported with from xyz import * ?
if xyz module defines an __all__ variable, it will import all the names defined in this sequence, otherwise it will import all names, except these which start with an underscore.
Note Many libraries have sub-modules. For example the standard library urllib includes sub-modules like urllib.request, urllib.errors, urllib.response etc. A common point of confusion is that
from urllib import *
would import all these sub-modules. That is NOT the case: one needs to explicitly imports these separately with, say, from urllib.request import * etc. This incidentally is not specific to import *, plain import will not import sub-modules either (but of course, the * which is often a shorthand for "everything" may mislead people in thinking that all sub-modules and everything else would be imported).
A: Yes, it does. It imports everything (that is not a private variable, i.e.: variables whose names start with _ or __), and you should try not to use it according to "Properly importing modules in Python" to avoid polluting the local namespace.
It is enough, but generally you should either do import project.model, which already imports __init__.py, per "Understanding python imports", but can get too wordy if you use it too much, or import project.model as pm or import project.model as model to save a few keystrokes later on when you use it.
Follow Alex's advice in "What exactly does "import *" import?"
A: If project.model is a package, the module referred to by import project.model is from .../project/model/__init__.py. from project.model import * dumps everything from __init__.py's namespace into yours. It does not automatically do anything with the other modules in model. The preferred style is for __init__.py not to contain anything.
Never ever ever ever ever use import *. It makes your code unreadable and unmaintainable.
A: Here is a nice way to see what star / asterisk ( * ) has imported from a module:
before = dir()
from math import *
after = dir()
print(set(after) - set(before))
returns:
{'modf', 'pow', 'erfc', 'copysign', 'sqrt', 'atan2', 'e', 'tanh', 'pi', 'factorial', 'cosh', 'expm1', 'cos', 'fmod', 'frexp', 'log', 'acosh', 'sinh', 'floor', 'isclose', 'lgamma', 'ceil', 'gcd', 'ldexp', 'hypot', 'radians', 'atan', 'isnan', 'atanh', 'before', 'isinf', 'fabs', 'isfinite', 'log10', 'nan', 'tau', 'acos', 'gamma', 'asin', 'log2', 'tan', 'degrees', 'asinh', 'erf', 'fsum', 'inf', 'exp', 'sin', 'trunc', 'log1p'}
I was working with my own module, importing everything explicitly but the list of stuff to import was getting too long. So, had to use this method to get a list of what * had imported.
A: If the module in question (project.model in your case) has defined a list of stings named __all__, then every named variable in that list is imported. If there is no such variable, it imports everything.
A: It import (into the current namespace) whatever names the module (or package) lists in its __all__ attribute -- missing such an attribute, all names that don't start with _.
It's mostly intended as a handy shortcut for use only in interactive interpreter sessions: as other answers suggest, don't use it in a program.
My recommendation, per Google's Python style guide, is to only ever import modules, not classes or functions (or other names) from within modules. Strictly following this makes for clarity and precision, and avoids subtle traps that may come when you import "stuff from within a module".
Importing a package (or anything from inside it) intrinsically loads and executes the package's __init__.py -- that file defines the body of the package. However, it does not bind the name __init__ in your current namespace (so in this sense it doesn't import that name). | unknown | |
d6919 | train | Can you make the same query (actually, better use a different parameters, to avoid the cost of caching) and check again?
The most common reason for this to take so long is that you are paying for the first time connection and establishing of the document store setup.
The strange part here is that you are doing this on the local host, so I would expect this to be very fast, even on the initial call.
You can use Fiddler (change the url to be: "http://localhost.fiddler:8080" so it will capture it) to see what are the costs on the network.
I have seen stuff like that happen because of anti virus and packet inspection utils. | unknown | |
d6920 | train | The .map method here is requiring you to pass a function with has a parameter which is a nullable user (User?), and return a nullable user. But you have defined the parameter to be a non-nullable user. Add a ? to the type of your parameter to make it nullable.
Stream<User?> get currentUser {
return _firebaseAuth.authStateChanges().map((User? user){
return user != null ? User.fromFirebase(user, 0) : null;
});
}
Update
I used CLASS User, at the same time I used OBJECT User from Firebase.This led to confusion as I used the same name for two completely different constructs.
Stream<Client?> get currentUser {
return _firebaseAuth
.authStateChanges()
.map((User? user) =>
user != null ? Client.fromFirebase(user) : null);
} | unknown | |
d6921 | train | This type of plot is a stacked bar plot. To produce it most easily with ggplot2, you need to transform your data into long format, so that one column has all the counts for both male and female, and another column contains a factor variable with the labels "Male" and "Female". You can do this using tidyr::pivot_longer:
library(ggplot2)
library(tidyr)
pivot_longer(df, cols = c(Females, Males)) %>%
ggplot() +
geom_col(mapping = aes(x = AgeClasses, y = value, fill = name)) +
labs(x = "Age", y = "Count", fill = "Gender")
A: Try the following code:
AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99')
Frequencies <- c(1000,900,800,700,600,500,400,300,200,100)
SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65)
Females <- SexRatioFM*Frequencies
Males <- Frequencies-Females
df <- data.frame(AgeClasses=AgeClasses, Females=Females, Males=Males)
df <- reshape2::melt(df, id.vars = 'AgeClasses')
library(ggplot2)
ggplot(df) +
geom_bar(mapping = aes(x = AgeClasses, y = value, fill=variable), stat = "identity")
A: Allan is right, but to make the one in the plot, you need the bars superposed rather than stacked. I did it like this:
library(ggplot2)
library(dplyr)
AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99')
Frequencies <- c(1000,900,800,700,600,500,400,300,200,100)
SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65)
df <- tibble(
Females = c(SexRatioFM*Frequencies),
Males = c(Frequencies-Females),
AgeClasses = AgeClasses,
Frequencies=Frequencies,
SexRatioFM = SexRatioFM)
df %>% select(AgeClasses, Males, Females) %>%
tidyr::pivot_longer(cols=c(Males, Females), names_to = "gender", values_to="val") %>%
ggplot() +
geom_bar(mapping = aes(x = AgeClasses, y=val, fill=gender, alpha=gender), stat="identity", position="identity") +
scale_alpha_manual(values=c(.5, .4))
A: You'll need to revamp how you create your sample dataframe. Here's one way to do it:
df <- data.frame(
AgeClasses = c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99'),
Frequencies = c(1000,900,800,700,600,500,400,300,200,100),
SexRatioFM = c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65))
df$Females = df$SexRatioFM*df$Frequencies
df$Males = df$Frequencies-df$Females
library(ggplot2)
ggplot(df) +
geom_bar(mapping = aes(x = AgeClasses, y = Females), fill="purple", stat = "identity", alpha=.8) +
geom_bar(mapping = aes(x = AgeClasses, y = Males), fill="navy blue", stat = "identity", alpha=.4)
And you should get something like this: | unknown | |
d6922 | train | As of Liferay 6.1 RC, the path has changed to /api/jsonws (from tunnel-web/jsonws).
Most (if not all) public services should be registered by default. | unknown | |
d6923 | train | As your applications are separate, essentially in the background meaning a different application ID and set of keys then merging the logins will not be possible. The authentication is based on OAuth so each application is treated as a separate resource meaning you'll need a valid token to authenticate requests against it.
Think of it another way, if you login to say Facebook or Twitter who both use OAuth then you login to the website, you have to login to the application on the mobile device again, that token cannot be used for another application.
A: It depends on the browser you were using.
If you were using the same browser for the web app and console app, the Azure AD will issue the cookies when you first time. And then the second sign-in request should be sign-in without users enter the credential again based on the cookies. | unknown | |
d6924 | train | Needed to add a client-config.wsdd to my project and add the following line:
<transport name="jms" pivot="java:com.ibm.mq.soap.transport.jms.WMQSender"/>
To override the client-config in axis.jar. I thought this was already done in this call:
com.ibm.mq.soap.Register.extension();
It still complained about the connection factory. Apparently it didn't understand the URL and I had to replace all & with & and remove the ports(it defaults to 1414 anyway..)
EDIT:
The IllegalArgumentException: noCFName occurs because of the ORDER of the external libraries. The jars in MQ_INSTALLATION_PATH/java/lib must be compiled before the jars in MQ_INSTALLATION_PATH/java/lib/soap. | unknown | |
d6925 | train | It looks like you're trying to run a class compiled with Java 8 on an older version of the JVM. Is that Tanuki wrapper honouring the JAVA_HOME variable that you set? What happens if you run it without going through the wrapper?
See here: How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
Edit: Also, I see that your path refers to both JDK 1.7 and JDK 1.8. I would try to remove the reference to JDK 1.7 to see if that makes a difference. | unknown | |
d6926 | train | I'm not sure is this what you mean, but I'll give it a shot: I found this hack some time ago
const isDebuggingEnabled = (typeof atob !== 'undefined');
A: This seems to work for now:
const debuggingEnabled = !!window.navigator.userAgent;
As window.navigator.userAgent is undefined on android and ios | unknown | |
d6927 | train | We are doing something similar. Our host is a .NET Framework 4.7.1 project:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net471</TargetFramework>
<IsPackable>true</IsPackable>
<PlatformTarget>x86</PlatformTarget>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.6" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business.csproj" />
<ProjectReference Include="..\Apis.Shared.csproj" />
<ProjectReference Include="..\Apis.Contracts.csproj" />
</ItemGroup>
</Project>
And our library projects are NetStandard2.0:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
</Project>
Program.cs looks like this:
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Startup.cs looks like this:
public class Startup
{
public Startup(IHostingEnvironment hostingEnvironment)
{
Settings = new AppSettings(hostingEnvironment);
}
public AppSettings Settings { get; private set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOptions();
// any other services registrations...
var builder = new ContainerBuilder();
// all autofac registrations...
builder.Populate(services);
return new AutofacServiceProvider(builder.Build(););
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
} | unknown | |
d6928 | train | Before Unity starts write these lines to pass the current language into unity
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];
[[NSUserDefaults standardUserDefaults] setObject: preferredLang forKey: @"language"];
[[NSUserDefaults standardUserDefaults] synchronize];
A: Definitely don't create a new app for each locale. iOS apps are localizable and iTunes Connect allows you to enter different metadata for each language.
A: You dont need to make a new app for each language. Try following a guide like SmoothLocalize's tutorial or This one.
Then you'll have a Localizable.strings file you need to translate. I usually use SmoothLocalize.com as my translation services, because its cheap and super easy, but you can look around for others or even try to find individual translators yourself. | unknown | |
d6929 | train | var window = window.open(url, windowName, [windowFeatures]); moidify the dom on the window object.
A: Not sure if you can do it in a separate window. However, for validation you can use the window.confirm function natively build into the browsers. Here is an example:
// window.confirm returns a boolean based on the user action
let validate = window.confirm('Do you want to continue?');
if (validate) {
console.log('validated');
} else {
console.log('not validated');
}
A: You can use in your script something like:
window.alert("what you want here"); | unknown | |
d6930 | train | Looking at your code, I see that you're adding your VBox to the TileGroup as follows:
table.addElement(vbox);
But then you're trying to remove it using removeChild():
t.parent.removeChild(t);
The proper method to add/remove items to/from Spark containers is add/removeElement():
var t:IVisualElement = IVisualElement(event.target);
t.parent.removeElement(t); | unknown | |
d6931 | train | You can get the phone number of incoming SMS in the following manner.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String string = "";
String phone = "";
if (bundle != null)
{
//---receive the SMS message--
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
phone = msgs[i].getOriginatingAddress(); // Here you can get the phone number of SMS sender.
string += msgs[i].getMessageBody().toString(); // Here you can get the message body.
}
}
And important thing you need is to mention permission in menifest file.(i.e. ). And in your Broadcast receiver class you have to mention <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"> in your intent-filter.
A: Use the getOriginatingAddress method.
A: Set the correct manifest file settings for receiving an incoming SMS. | unknown | |
d6932 | train | Try the short version of IF
var result = cmd.Parameters["@error"].Value;
message = (result == DBNull.Value) ? string.Empty : result.ToString();
or simply
var result = cmd.Parameters["@error"].Value;
message = (result == DBNull.Value) ? string.Empty : result.ToString();
or
var result = cmd.Parameters["@error"].Value;
message = ((result == DBNull.Value) || (result == DBNull.Value)) ? string.Empty : result.ToString();
A: A shorter alternative:
message = cmd.Parameters["@error"].Value as string ?? ""; | unknown | |
d6933 | train | if all you need is to isolate those 2 numbers from that string try this:
def parse(text):
return [float(i) for i in text.split('[', 1)[1].split(']', 1)[0].split(', ')]
long_lat = parse(your_string_var)
EDIT:
oh and to get the id something like this should do:
def parse2(text):
return text.split('_', 1)[1].split(' ', 1)[0]
id = parse2(your_string_var)
A: This is Javasascript script, so BeautifulSoup won't execute/parse it. You can use re module to get the information.
For example:
import re
txt = '''var marker_9795626cfd584471ab4406d756a00baf = L.marker([19.041691972000024, 72.85052482000003],{}).addTo(feature_group_ad623471194f451d9f1cf7fc718747c5);'''
marker_id, lat, lon = re.search(r'marker_([a-f\d]+).*?\[(.*?), (.*?)\]', txt).groups()
print(marker_id)
print(lat)
print(lon)
Prints:
9795626cfd584471ab4406d756a00baf
19.041691972000024
72.85052482000003
EDIT: To parse the variables from file, you can use this script:
import re
with open('<YOUR FILE>', 'r') as f_in:
for line in f_in:
m = re.search(r'marker_([a-f\d]+).*?\[(.*?), (.*?)\]', line)
if m:
marker_id, lat, lon = m.groups()
print(marker_id, lat, lon)
EDIT2: New version:
import re
with open('<YOUR FILE>', 'r') as f_in:
data = f_in.read()
for marker_id, lat, lon in re.findall(r'marker_([a-fA-F\d]+).*?\[(.*?),\s*(.*?)\]', data):
print(marker_id, lat, lon) | unknown | |
d6934 | train | Use regex /\b[0-9]+:[0-9]+\b/. Explanation:
*
*\b - word boundary
*[0-9]+ - 1+ digits
*: - literal colon
*[0-9]+ - 1+ digits
*\b - word boundary
I do not know your specific use in selenium, but here is an example:
src = 'Media: a few minutes ago, 3:25 pm uts'
pattern = re.compile(r'(\\b[0-9]+:[0-9]+\\b)')
match = pattern.search(src)
print match.groups()[0]
Output:
3:25 | unknown | |
d6935 | train | You actually can use something similar to $1:
for (var i=0; i<len; i++) {
var e = arr[i], //<- strings
re = new RegExp(e,"ig");
target.html(
target.html().replace(
re, "<span class='rep'>$&</span>"
)
); //you could also have used $1 to refer to the first backreference, instead of the entire match
}
Your second problem is less clear to me. Single quotes are not special characters in regexes.
I could not replicate your other problem. Here is a working example: http://jsfiddle.net/Xsjt7/1/
A: if you want to use $1 and the arr is just an array of strings you could join it:
var arr = ["what","not make any sense","n't make any sense","it's"];
var target = $('#mydiv');
var re = new RegExp("(" + arr.join("|") +")","ig");
target.html(
target.html().replace(re, "<span class='rep'>$1</span>")
); | unknown | |
d6936 | train | As so many have said - it does nothing.
Why is it there? Here is a possibility …
I am fed up with bad coders on my team not checking return values of functions.
So, since we develop in Linux with the GCC compiler, I add __attribute__((warn_unused_result)) to the declaration of all of my typed functions. See also this question for a MS VC equivalent.
If the user does not check the return value, then the compiler generates a warning.
The cowboys, of course, have gamed the system and code if (foo() != SUCCESS) ; which satisfies the compiler (although it does not satisfy me :-).
A: A single ; is the null statement which does nothing. It's often used in long if/else chains like:
if (a == 1) {
// Do nothing.
;
}
else if (...) {
...
}
else if (...) {
...
}
This could also be written as:
if (a != 1) {
if (...) {
...
}
else if (...) {
...
}
}
The latter adds another level of indentation but IMO, it's clearer. But null statements can sometimes be useful to avoid excessive indentation if there are multiple branches without code.
Note that an empty compound statement (also called block) has the same effect:
if (a == 1) {}
Technically, you only need the semicolon if you want to use an expression statement directly:
if (a == 1) ;
else if (...) { ... }
else if (...) { ... }
So writing {;} is redundant and only serves a dubious illustrative purpose.
Another example from the C standard where the null statement is used to supply an empty loop body:
char *s;
/* ... */
while (*s++ != '\0')
;
But here I'd also prefer an empty compound statement.
A: It's an empty statement. A single semicolon by itself performs no operation.
In this context, it means that if the if condition is true, do nothing.
Without an else section, there is not much use to this code. If there is, then it's a matter of style whether the condition should be inverted and should contain just a non-empty if portion.
In this case it's a simple conditional, so style-wise it's probably better to invert it, however if the condition is more complicated it may be clearer to write this way. For example, this:
if ((a==1) && (b==2) && (c==3) && (d==4)) {
;
} else {
// do something useful
}
Might be clearer than this:
if (!((a==1) && (b==2) && (c==3) && (d==4))) {
// do something useful
}
Or this:
if ((a!=1) || (b!=2) || (c!=3) || (d!=4)) {
// do something useful
}
A better example from the comments (thanks Ben):
if (not_found) {
;
} else {
// do something
}
Versus:
if (!not_found) {
// do something
}
Which method to use depends largely on exactly what is being compared, how many terms there are, how nested the terms are, and even the names of the variables / functions involved.
Another example of when you might use this is when you have a set of if..else statements to check a range of values and you want to document in the code that nothing should happen for a particular range:
if (a < 0) {
process_negative(a);
} else if (a >=0 && a < 10) {
process_under_10(a);
} else if (a >=10 && a < 20) {
; // do nothing
} else if (a >=20 && a < 30) {
process_20s(a);
} else if (a >= 30) {
process_30s_and_up(a);
}
If the empty if was left out, a reader might wonder if something should have happened there and the developer forgot about it. By including the empty if, it says to the reader "yes I accounted for this and nothing should happen in this case".
Certain coding standards require that all possible outcomes be explicitly accounted for in code. So code adhering to such a standard might look something like this.
A: It's called null statement.
From 6.8.3 Expression and null statements:
A null statement (consisting of just a semicolon) performs no
operations.
In this particular example if(a==1){;}, it doesn't do anything useful (except perhaps a bit more obvious) as it's same as if(a==1){} or if(a==1);.
A: It is basically an null/empty statement, which does nothing, and is as expected benign (no error) in nature.
C Spec draft N1570 clarifies that:
*
*the expressions are optional: expression[opt] ;
*A null statement (consisting of just a semicolon) performs no operations.
On the other hand, Bjarne quotes in his C++ book #9.2 Statement Summary:
A semicolon is by itself a statement, the empty statement.
Note that these two codes, if(1) {;} and if(1) {}, have no difference in the generated gcc instructions.
A: ; on its own is an empty statement. If a is an initialised non-pointer type, then
if(a==1){;}
is always a no-op in C. Using the braces adds extra weight to the assertion that there is no typo. Perhaps there is an else directly beneath it, which would execute if a was not 1.
A: No purpose at all. It's an empty statement. It's possible that the developer wanted to do something if a was not 1 in which case the code would be something like (even though the ; can still be omitted) :
if(a==1)
{
;
}
else
{
//useful code...
}
But in that case, it could've easily been written as if(a != 1).
Note however, if this is C++(tags aren't clear yet) then there would be a possibility that the operator== of type a was overloaded and some side effects could've been observed. That would mean that the code is insane though.
A: It is so called null statement. It is a kind of the expression statement where the expression is missed.
Sometimes it is used in if-else statements as you showed when it is easy to write the if condition than its negation (or the if condition is more clear) but the code should be executed when the if condition is evaluated to false.
For example
if ( some_condition )
{
; // do nothing
}
else
{
// here there is some code
}
Usually the null statement is used for exposition only to show that for example body of a function, or a class constructor or a for loop is empty. For example
struct A
{
A( int x ) : x( x )
{
;
}
//...
};
Or
char * copy_string( char *dsn, const char *src )
{
char *p = dsn;
while ( ( *dsn++ = *src++ ) ) ;
^^^
return p;
}
Here the null statement is required for the while loop. You could also rewrite it like
while ( ( *dsn++ = *src++ ) ) {}
Sometimes the null statement is required especially in rare cases when goto statement is used. For example in C declarations are not statements. If you want to pass the program control to a point before some declaration you could place a label before the declaration. However in C a label may be placed only before a statement. In this case you could place a null statement with a label before the declaration. For example
Repeat:;
^^^
int a[n];
//....
n++;
goto Repeat;
Pay attention to the null statement after the label. If to remove it then the C compiler will issue an error.
This trick also is used to pass the program control to the end of a compound statement. For example
{
// some code
goto Done;
//...
Done:;
}
Though you should not use the goto statement but you should know about these cases.:)
A: Why would you do it? I do similar things all the time when debugging to give me something that (I hope) won't be optimized away so I can put a break point on it.
Normally though I make it obvious its a debug mark
if( (a==1) && (b==2) && (c==3) && (d==4) ){
int debug=1;
}
Otherwise I end up with weird little bits of code stuck everywhere that make absolutely no sense even to me.
But that is not guarantee that's what this was.
A: ; is an empty statement noop
What is its purpose?
Sometimes we just want to compare things like in this case the equality of a and 1. With primitive types like integer, this will set condition register so if you have after this if something like if(a > 1) or if(a < 1), and a is not changed in the meantime, this might not be evaluated again depending on the compiler decision.
This code
int f(int a){
if(a == 1){;}
if(a > 1){return 3;}
if(a < 1){return 5;}
return 0;
}
will give
.file "c_rcrYxj"
.text
.p2align 2,,3
.globl f
.type f, @function
f:
.LFB0:
.cfi_startproc
cmpl $1, 4(%esp)
jle .L6
movl $3, %eax
ret
.p2align 2,,3
.L6:
setne %al
movzbl %al, %eax
leal (%eax,%eax,4), %eax
ret
.cfi_endproc
.LFE0:
.size f, .-f
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"
.section .note.GNU-stack,"",@progbits
The comparison is done only once cmpl $1, 4(%esp), exactly where if(a==1) is written.
A: You probably already know that the semicolon is an empty statement. Concerning the actual question "what purpose does this semicolon serve", the answer is (unless the author of this code wanted to enliven the code with some weird emoticon), that it serves absolutely no purpose at all. That is, {;} is completely equivalent to {} in any context (where a statement is expected, which I think is the only place where {;} can be used). The presence of the semicolon changes a compound statement with 0 constituent statements into a compound statement with 1 constituent statement which is an empty statement, but the two cases are equivalent as far as semantics is concerned.
I'll add a personal opinion that for readability concern of not being accidentally overlooked by a reader of the code, {;} is no better than {} (if it were, then maybe {;;;;;;;;} would be better still), though both are considerably better than a lone ; (and as a consequence the language would have been better off without allowing ; as empty statement at all, since replacing it with {} is always advantageous). | unknown | |
d6937 | train | Try adding .json to the end, like below, to get a JSON response Studio can parse.
/2010-04-01/Accounts/{YourAccountSid}/Recordings/{RecordingSid}/Transcriptions.json | unknown | |
d6938 | train | One idea would be to create a macro that runs when the workbook is opened and it sets the row height using the Range.RowHeight property, here:
https://msdn.microsoft.com/en-us/library/office/ff193926.aspx
A: If anyone ever has a similar issue, I managed to find a workaround. Instead of using SSIS I'm using SSRS where I keep the cell height by adding an "invisible (white text on white background) column at the end. I set up an SSRS subscription to automatically export the data and send as an Excel. | unknown | |
d6939 | train | If you're using Selenium with Python, you may be able to take advantage of the Page Object Model abilities of the SeleniumBase framework. Here's some code examples of that:
File 1 - google_objects.py:
class HomePage(object):
dialog_box = '[role="dialog"] div'
search_box = 'input[title="Search"]'
list_box = '[role="listbox"]'
search_button = 'input[value="Google Search"]'
feeling_lucky_button = """input[value="I'm Feeling Lucky"]"""
class ResultsPage(object):
google_logo = 'img[alt="Google"]'
images_link = "link=Images"
search_results = "div#center_col"
File 2 - google_test.py:
from seleniumbase import BaseCase
from .google_objects import HomePage, ResultsPage
class GoogleTests(BaseCase):
def test_google_dot_com(self):
self.open("https://google.com/ncr")
self.type(HomePage.search_box, "github")
self.assert_element(HomePage.list_box)
self.assert_element(HomePage.search_button)
self.assert_element(HomePage.feeling_lucky_button)
self.click(HomePage.search_button)
self.assert_text("github.com", ResultsPage.search_results)
self.assert_element(ResultsPage.images_link)
(Example taken from the SeleniumBase samples/ folder)
As seen above, reusable selectors/objects from File 1 are used in File 2, and could also be reused in many other files as well.
Here's a longer example, test_page_objects.py, which puts methods into page objects:
from seleniumbase import BaseCase
class GooglePage:
def go_to_google(self, sb):
sb.open("https://google.com/ncr")
def do_search(self, sb, search_term):
sb.type('input[title="Search"]', search_term + "\n")
def click_search_result(self, sb, content):
sb.click('a[href*="%s"]' % content)
class SeleniumBaseGitHubPage:
def click_seleniumbase_io_link(self, sb):
link = '#readme article a[href*="seleniumbase.io"]'
sb.wait_for_element_visible(link)
sb.js_click(link)
sb.switch_to_newest_window()
class SeleniumBaseIOPage:
def do_search_and_click(self, sb, search_term):
if sb.is_element_visible('[for="__search"] svg'):
sb.click('[for="__search"] svg')
sb.type('form[name="search"] input', search_term)
sb.click("li.md-search-result__item h1:contains(%s)" % search_term)
class MyTests(BaseCase):
def test_page_objects(self):
search_term = "SeleniumBase GitHub"
expected_text = "seleniumbase/SeleniumBase"
GooglePage().go_to_google(self)
GooglePage().do_search(self, search_term)
self.assert_text(expected_text, "#search")
GooglePage().click_search_result(self, expected_text)
SeleniumBaseGitHubPage().click_seleniumbase_io_link(self)
SeleniumBaseIOPage().do_search_and_click(self, "Dashboard")
self.assert_text("Dashboard", "main h1")
This provides a lot of different possibilities for script reusability. | unknown | |
d6940 | train | You could try
if (column == "PressureChange")
{
if (sortDirection == "ascending")
{
testResults = testResults.OrderBy(t => double.Parse(t.PressureChange));
}
else
{
testResults = testResults.OrderByDescending
(t => double.Parse(t.PressureChange));
}
}
... but it depends whether that method is supported by LINQ to SQL. To be honest, it sounds like you've got bigger problems in terms of your design: if you're trying to store a double value in the database, you shouldn't be using a varchar field to start with. Fix your schema if you possibly can.
EDIT: Note that based on the information on this page about LINQ to SQL and Convert.* it looks like Convert.ToDouble should work, so please give us more information about what happened when you tried it.
A: Rather use TryParse to avoid exceptions. In this code I used 0.0 as a default value if it could not parse the string.
double temp = 0.0;
if (column == "PressureChange")
{
if (sortDirection == "ascending")
testResults = testResults.OrderBy(t => (double.TryParse(t.PressureChange.toString(), out temp) ? temp : 0.0)).ToList();
else
testResults = testResults.OrderByDescending(t => (double.TryParse(t.PressureChange.toString(), out temp) ? temp : 0.0)).ToList();
}
A: I have not tested it but you can use an extension method like this:
public class StringRealComparer : IComparer<string>
{
public int Compare(string s1, string s2)
{
double d1;
double d2;
double.tryParse(s1, out d1);
double.TryParse(s2, out d2);
return double.Compare(d1, d2);
}
} | unknown | |
d6941 | train | Well, you can also use position: fixed; bottom: 0;, which will stick the element to the bottom of the window. That means it won't even scroll with the rest of the page.
When you use that for a full-width footer or the like (the most likely use case), you'd then need to add a margin to the rest of the page content so that it doesn't get hidden behind (or hide) the footer.
Other than that you're pretty much stuck with the options you mentioned.
Full documentation on the position property can be found here:
https://developer.mozilla.org/en-US/docs/Web/CSS/position
A: You can also use position: fixed
.elem {
position: fixed;
bottom: 0;
}
Or you can use Flex then set your element to align-self: flex-end
e.g.
.container {
height: 150px;
width: 150px;
display: flex;
display: -webkit-flex;
-webkit-flex-direction: row;
flex-direction: row;
border: 1px solid red;
}
.container div {
-webkit-align-self: flex-end;
align-self: flex-end
}
Fiddle | unknown | |
d6942 | train | @RequestMapping annotation makes controller to be initialized eagerly despite the fact that it is also annotated with @Lazy(value=true).
In your case, removing @RequestMapping annotation should make the controller initialize lazily. Though I do not know if it is possible to use @RequestMapping annotation and have that controller load lazily, I did not manage to achieve it (solved my issue without making the controller load lazily, but that is out of scope of this question). | unknown | |
d6943 | train | I have read the tutorial you give as a link. That tutorial doesn't give the full code. According to what I see the variables you mention must be defined.
For SET_TIME_REQUEST_ID usually you add this at the beginning with something like that
private static final int SET_TIME_REQUEST_ID = 1;
because onActivityResult(int, int, Intent)
That ID is your internal identification. I put 1 but you can put any number. It is an ID for you so that when the activity closes you can fetch the result.
So yes you have to define it.
Same for secondsSet.
The type seems to be Integer because the parent.getItemAtPostion is cast to Integer. It is used but not defined. Seems to me to be a global variable. The ones you put at the top of your class.
So yes you have to define it also :-)
And finally it is the same for context. It is used but not declared. It seems the tutorial you use declares all these variable globally.
EDIT
The manifest file tells the system that an intent (activity) exist.
You should have some thing like that
<activity
android:name="com.gelliesmedia.countdown.CountdownSetTime">
</activity> | unknown | |
d6944 | train | Try this
viewController .h
NSTimer *timer;
viewcontroller.m
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(pollTime)
userInfo:nil
repeats:YES];
- (void) viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[timer invalidate];
}
A: Declare NSTimer *myTimer in .h file.
Assign instance as tom said like this
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f
target:self
selector:@selector(update)
userInfo:nil
repeats:YES];
Stop and Invalidate using this
- (void) viewDidDisappear:(BOOL)animated
{
[myTimer invalidate];
myTimer = nil;
}
A: Yes, you would use the - (void)invalidate instance method of NSTimer.
Of course, to do that, you would have to save the NSTimer instance returned from [NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:] into an ivar or property of your view controller, so you can access it in viewDidDisappear.
A: invalidate Method of NSTimer is use for stop timer
- (void) viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[self.timer invalidate];
self.timer = nil;
}
If you are not ARC then don't forget [self.timer release];
A: For stopping or invalidating NSTimer first you have to create instance for NSTimer in Globally.
Timer=[NSTimer scheduledTimerWithTimeInterval:0.1f
target:self
selector:@selector(update)
userInfo:nil
repeats:YES];
after that try like this,
if (Timer != nil) {
[Timer invalidate];
Timer = nil;
} | unknown | |
d6945 | train | A simple solution is to create our own widget so we overwrite the mouseDoubleClickEvent method, and you could overwrite paintEvent to draw the widget:
#ifndef DOUBLECLICKEDWIDGET_H
#define DOUBLECLICKEDWIDGET_H
#include <QWidget>
#include <QPainter>
class DoubleClickedWidget : public QWidget
{
Q_OBJECT
public:
explicit DoubleClickedWidget(QWidget *parent = nullptr):QWidget(parent){
setFixedSize(20, 20);
}
signals:
void doubleClicked();
protected:
void mouseDoubleClickEvent(QMouseEvent *){
emit doubleClicked();
}
void paintEvent(QPaintEvent *){
QPainter painter(this);
painter.fillRect(rect(), Qt::green);
}
};
#endif // DOUBLECLICKEDWIDGET_H
If you want to use it with Qt Designer you can promote as shown in the following link.
and then connect:
//new style
connect(ui->widget, &DoubleClickedWidget::doubleClicked, this, &MainWindow::onDoubleClicked);
//old style
connect(ui->widget, SIGNAL(doubleClicked), this, SLOT(onDoubleClicked));
In the following link there is an example. | unknown | |
d6946 | train | The difference is the type of list you are running on.
box1 is a NodeList (a.k.a a live node list) which is updated when the DOM changes. box2 is an array, which is a non-live list - so changing the DOM doesn't affect it.
What happens when you iterate on box1 is that on every class toggle, the box1 list is updated, which causes the overhead.
Here's a test you can easily run:
var container = document.getElementById('box-container');
var button = document.getElementById('button');
for (var i = 0; i < 6000; i++) { // added 3000 more to challenge modern browsers...
var div = document.createElement('div');
div.classList.add('box');
div.index = i;
container.appendChild(div);
}
button.addEventListener('click', function () {
var box1 = container.getElementsByClassName('box');
for (var i = 1; i < box1.length; i += 2) {
box1[i].classList.toggle('gray');
}
var deadBox1 = [];
for (i = 0; i < box1.length; i++) {
deadBox1[i] = box1[i];
}
for (var i = 1; i < deadBox1.length; i += 2) {
deadBox1[i].classList.toggle('gray');
}
var box2 = container.querySelectorAll('.box');
for (i = 1; i < box2.length; i += 2) {
box2[i - 1].classList.toggle('gray');
}
});
Now run the chrome performance (or timeline) tool. You can see the diff here: | unknown | |
d6947 | train | Try this instead DEMO
$('input[type="checkbox"]').click(function() {
($(this).is(":checked")) ? $(this).next().hide() : $(this).next().show();
});
A: Try to hide all the divs with class div1 initially,
$(".div1").hide();
$('input[type="checkbox"]').click(function() {
$(this).next('.div1').toggle(!this.checked); //toggle(false) will hide the element
});
And toggle the visibility of the relevant div element with class div1 by using next() and toggle()
DEMO | unknown | |
d6948 | train | DarkBee's answer is good, but if your macro is in the same twig file that's calling it then you will still need to import it like so:
{% import _self as my_macros %}
{{ my_macros.widget_prototype(...) }}
Seems a bit counter-intuitive but that's how it is.
A: You need to import the macro, not include it
{% import "my_macro.twig" as my_macro %}
{{ my_macro.function(arg1) }} | unknown | |
d6949 | train | There's only one connection there - and a command using the same connection. Both will be disposed.
This is effectively:
using(OleDbConnection con = new OleDbConnection(conString))
{
using(OleDbCommand command = con.CreateCommand())
{
} // command will be disposed here
} // con will be disposed here | unknown | |
d6950 | train | One error is that your checktables function corrupts your linked list structure by calling delete on one of the nodes:
found = temp;
delete found; // Discard
What you've just done in those lines above is to have a linked list with a broken (invalid) link in it. Any functions that now traverses the list (like displaytables) will now hit the broken link, and things start to go haywire.
To delete a node from a linked list, you have to not just call delete, but adjust the link in waitinglist that used to point to that deleted node and have it point to the next node after the deleted one.
Think of it like a real chain -- if one of the links in the chain needs to be removed, you have to physically remove it, and hook the link before it to the next good link. You didn't do this step.
I won't write the code for that, but this is what you should have seen much earlier in the development of your program. Better yet would have been to write a singly-linked list class that adds and removes nodes correctly first. Test it, and then once it can add and remove nodes successfully without error, then use it in your larger program. | unknown | |
d6951 | train | There are a couple of things wrong that I see right away. The primary problem you're having is a network problem--not a code problem or a Spring Social problem. Even if your network admin says you can see Facebook, the exception you show tells me otherwise. That's something you'll need to work out on your end.
Once you get past that, I doubt this will work anyway. You obtain your access token via authenticateClient(), which only grants you a client token. But then you try to use it for user-specific requests, such as obtaining the home feed. You must have a user token to do that operation and you can only get a user token via user authorization, aka the "OAuth Dance". Spring Social's ConnectController can help you with that. | unknown | |
d6952 | train | Is there an ID for your snapshot.data.documents[index]? If yes, add it to the end.
onTap: () {
print("Tapped ${snapshot.data.documents[index]['the property you want']}");
}, | unknown | |
d6953 | train | Pretty sure you need this to auth: https://learn.microsoft.com/es-es/javascript/api/azure-arm-resource/subscriptionclient?view=azure-node-latest
and this call to get locations: https://learn.microsoft.com/es-es/javascript/api/azure-arm-resource/locationlistresult?view=azure-node-latest
Node SDK repo: https://github.com/Azure/azure-sdk-for-node | unknown | |
d6954 | train | This question was answered on the jQuery forum
It's jQuery.extend | unknown | |
d6955 | train | Updated @Luca Angeletti answer for Swift 3.0.1
extension String {
func image() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0);
UIColor.white.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(CGRect(origin: CGPoint(), size: size))
(self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
A: Swift 4.2
I really liked @Luca Angeletti solution. I hade the same question as @jonauz about transparent background. So with this small modification you get the same thing but with clear background color.
I didn't have the rep to answer in a comment.
import UIKit
extension String {
func emojiToImage() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.clear.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(CGRect(origin: CGPoint(), size: size))
(self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
A: Swift 5: ( with optional fontSize, imageSize and bgColor)
use it like this:
let image = "".image()
let imageLarge = "".image(fontSize:100)
let imageBlack = "".image(fontSize:100, bgColor:.black)
let imageLong = "".image(fontSize:100, imageSize:CGSize(width:500,height:100))
import UIKit
extension String
{
func image(fontSize:CGFloat = 40, bgColor:UIColor = UIColor.clear, imageSize:CGSize? = nil) -> UIImage?
{
let font = UIFont.systemFont(ofSize: fontSize)
let attributes = [NSAttributedString.Key.font: font]
let imageSize = imageSize ?? self.size(withAttributes: attributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
bgColor.set()
let rect = CGRect(origin: .zero, size: imageSize)
UIRectFill(rect)
self.draw(in: rect, withAttributes: [.font: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
A: Updated version of @Luca Angeletti's answer using UIGraphicsImageRenderer:
extension String {
func image() -> UIImage? {
let size = CGSize(width: 100, height: 100)
let rect = CGRect(origin: CGPoint(), size: size)
return UIGraphicsImageRenderer(size: size).image { (context) in
(self as NSString).draw(in: rect, withAttributes: [.font : UIFont.systemFont(ofSize: 100)])
}
}
}
A: Here's an updated answer with the following changes:
*
*Centered: Used draw(at:withAttributes:) instead of draw(in:withAttributes:) for centering the text within the resulting UIImage
*Correct Size: Used size(withAttributes:) for having a resulting UIImage of size that correlates to the actual size of the font.
*Comments: Added comments for better understanding
Swift 5
import UIKit
extension String {
func textToImage() -> UIImage? {
let nsString = (self as NSString)
let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
let stringAttributes = [NSAttributedString.Key.font: font]
let imageSize = nsString.size(withAttributes: stringAttributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) // begin image context
UIColor.clear.set() // clear background
UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
UIGraphicsEndImageContext() // end image context
return image ?? UIImage()
}
}
Swift 3.2
import UIKit
extension String {
func textToImage() -> UIImage? {
let nsString = (self as NSString)
let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
let stringAttributes = [NSFontAttributeName: font]
let imageSize = nsString.size(attributes: stringAttributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) // begin image context
UIColor.clear.set() // clear background
UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
UIGraphicsEndImageContext() // end image context
return image ?? UIImage()
}
}
A: Same thing for Swift 4:
extension String {
func emojiToImage() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.white.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(rect)
(self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
A: Updated for Swift 4.1
Add this extension to your project
import UIKit
extension String {
func image() -> UIImage? {
let size = CGSize(width: 40, height: 40)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.white.set()
let rect = CGRect(origin: .zero, size: size)
UIRectFill(CGRect(origin: .zero, size: size))
(self as AnyObject).draw(in: rect, withAttributes: [.font: UIFont.systemFont(ofSize: 40)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
The code above draws the current String to an Image Context with a white background color and finally transform it into a UIImage.
Now you can write
Example
Given a list of ranges indicating the unicode values of the emoji symbols
let ranges = [0x1F601...0x1F64F, 0x2702...0x27B0]
you can transform it into a list of images
let images = ranges
.flatMap { $0 }
.compactMap { Unicode.Scalar($0) }
.map(Character.init)
.compactMap { String($0).image() }
Result:
I cannot guarantee the list of ranges is complete, you'll need to search for it by yourself
A: This variation is based on @Luca's accepted answer, but allows you to optionally customize the point size of the font, should result in a centered image, and doesn't make the background color white.
extension String {
func image(pointSize: CGFloat = UIFont.systemFontSize) -> UIImage? {
let nsString = self as NSString
let font = UIFont.systemFont(ofSize: pointSize)
let size = nsString.size(withAttributes: [.font: font])
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let rect = CGRect(origin: .zero, size: size)
nsString.draw(in: rect, withAttributes: [.font: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
} | unknown | |
d6956 | train | In arbitrary-precision arithmetic, ball arithmetic is about twice as fast as interval arithmetic and uses half as much space. The reason is that only the center of a ball needs high precision, whereas in interval arithmetic, both endpoints need high precision. Details depend on the implementation, of course. (In practice, Arb is faster than MPFI by much more than a factor two, but this is largely due to implementation effort.)
In hardware arithmetic, balls don't really have a speed advantage over intervals, at least for scalar arithmetic. There is an obvious advantage if you look at more general forms of ball arithmetic and consider, for example, a ball matrix as a floating-point matrix + a single floating-point number for the error bound of the whole matrix in some norm, instead of working with a matrix of individual intervals or balls.
Joris van der Hoeven's article on ball arithmetic is a good take on the differences between ball and interval arithmetic: http://www.texmacs.org/joris/ball/ball.html
An important quote is: "Roughly speaking, balls should be used for the reliable approximation of numbers, whereas intervals are mainly useful for certified algorithms which rely on the subdivision of space."
Ignoring performance concerns, balls and intervals are usually interchangeable, although intervals are better suited for subdivision algorithms. Conceptually, balls are nice for representing numbers because the center-radius form corresponds naturally to how we think of approximations in mathematics. This notion also extends naturally to more general normed vector spaces.
Personally, I often think of ball arithmetic as floating-point arithmetic + error analysis, but with the error bound propagation done automatically by the computer rather than by hand. In this sense, it is a better way (for certain applications!) of doing floating-point arithmetic, not just a better way of doing interval arithmetic.
For computations with single numbers, error over-estimation has more to do with the algorithms than with the representation. MPFI guarantees that all its atomic functions compute the tightest possible intervals, but this property is not preserved as soon as you start composing functions. With either ball or interval arithmetic, blow-up tends to happen in the same way as soon as you run calculations with many dependent steps. To track error bounds resulting from large uncertainties in initial conditions, techniques such as Taylor models are often better than direct interval or ball arithmetic.
True complex balls (complex center + single radius) are sometimes better than rectangular complex intervals for representing complex numbers because the wrapping effect for multiplications is smaller. (However, Arb uses rectangular "balls" for complex numbers, so it does not have this particular advantage.) | unknown | |
d6957 | train | Try using to_date() with concat() Spark functions
from pyspark.sql.functions import concat, to_date, col, lit
timestampedDf = dropnullfields3.toDF()
timestampedDf = timestampedDf.withColumn("snap_timestamp", to_date(concat(col('year'), lit('-'), col('month'), lit('-'), col('day'))))
timestamped4 = DynamicFrame.fromDF(timestampedDf, glueContext, "timestamped4") | unknown | |
d6958 | train | Thank you thisfeller for push to the right direction!
The problem was that the default password change portlet is mentioned to be used only with password reset portlet that sends email to user etc. So I wrote my own portlet based on that reset password portlet but removed the finding of wanted user by token and instead just check who is logged in. | unknown | |
d6959 | train | You can use FlowLayoutPanel
Though, you might need to set the FlowDirection to TopDown
Just put those labels into the panel | unknown | |
d6960 | train | IsNumeric will match things like "2E+1" (2 times ten to the power of 1, i.e. 20) as that is a number in scientific format. "0D88" is also a number according to IsNumeric because it is the double-precision (hence the "D") version of "0E88".
You could use LIKE '####' to match exactly four digits (0-9).
If you had more complex match requirements, say a variable quantity of digits, you would be interested in Expressing basic Access query criteria as regular expressions. | unknown | |
d6961 | train | Learning OOP and learning about MVC is a good idea, before getting into PHP frameworks. Straight away you will have to make design decisions about where you should put different code. If you make the mistakes early, then to improve your design you will have to go back and fix up poor mistakes.
I read a nice answer recently: How to increase my "advanced" knowledge of PHP further? (quickly)
A: In general I'd say Yes it is a good idea. The reason being that many OO concepts get applied in frameworks so you will get lots of practical exposure to various patterns an constructs. | unknown | |
d6962 | train | You should declare String answer=""; inside doAgain function. Otherwise you will get cannot find symbol error in this line
while (incorrect(answer) != false);
Modify doAgain function to this
public static boolean doAgain() {
String answer="";
do {
Scanner kb = new Scanner(System.in);
// String answer; // remove this
System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
answer = kb.nextLine();
if (answer.equals("yes")) {
return true;
} else {
return false;
}
} while (incorrect(answer) != false);
}
A: Here a some mistakes you made:
*
*!answer.equals("yes") || !answer.equals("no") always returns true.
*answer in } while (incorrect(answer) != false); is out of scope. You need to declare String answer = ""; before the do-while loop.
*The loop never repeats, because of you if else which always returns in the loop.
The fixed code can be:
public static boolean doAgain() {
Scanner kb = new Scanner(System.in);
String answer = "";
do {
System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
answer = kb.nextLine();
} while (incorrect(answer)); // Better not use double negative
if (answer.equals("yes"))
return true;
else
return false;
}
public static boolean incorrect(String answer) {
if (answer.equals("yes") || answer.equals("no"))
return false; // answer is correct
else
return true; // answer is incorrect
} | unknown | |
d6963 | train | Vertica is a mass data database, and it prefers more efficient joins and existence checks than correlated sub-selects - what an EXISTS predicate boils down to - and what results in a slowing-down nested loop.
Put the datehired check into a LEFT JOIN predicate with a Common Table Expression - in a WITH clause. If the joined table's columns are NULL, the matching id does not exist, so finally just check for being NULL.
WITH
dh AS (
SELECT
id
, datehired
FROM date_hired
WHERE dh.office = 'Med-office'
)
SELECT
id
, nam
, CASE WHEN dh.id IS NOT NULL
THEN 1
ELSE 0
END AS decision
FROM new_table n
JOIN old_table e USING(id)
LEFT JOIN dh
ON e.id = = dh.id
AND (
dh.datehired <= e.interview_start_date
OR
dh.datehired BETWEEN e.interview_start_date AND e.last_job_date
) | unknown | |
d6964 | train | IMO approach is valid, make sure that APIs resource policy allows only assumed identity role to perform actions (assuming this is your use case).
You can also change the authorization type to Cognito and use the Cognito user access token and scopes to authorize access. Then you do not need to manage policies, see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-cross-account-cognito-authorizer.html. | unknown | |
d6965 | train | There are a few ways to solve this issue:
*
*Use a REDIS SENTINEL with failover capabilities. This way, if the primary REDIS instance goes down, the sentinel will automatically failover to the replica instance and your elements will not be lost.
*Use a REDIS CLUSTER. This will provide you with high availability and will ensure that your elements are not lost in the event of a failure.
*Use a REDIS Replication setup. This will provide you with a hot standby REDIS instance that can take over if the primary instance goes down.
*Use a REDIS Persistence setup. This will ensure that your elements are not lost in the event of a failure.
*Use a REDIS Backup setup. This will ensure that your elements are not lost in the event of a failure. | unknown | |
d6966 | train | Often when you stumble across a problem like this, you need to look at encapsulation rather than extension. Can't you use the MapView as a member variable?
If you check out the MapView API, it states that we must implement the Android life cycle for the MapView in order for it to function properly. So, if you use a MapView as a member variable, you need to override the following methods in your main activity to call the matching methods in the MapView:
onCreate(Bundle)
onResume()
onPause()
onDestroy()
onSaveInstanceState(Bundle)
onLowMemory()
As an example, your Activity would look like the following:
public final class MainActivity extends Activity {
private MapView mMapView;
@Override
public final void onCreate(final Bundle pSavedInstanceState) {
super(pSavedInstanceState);
this.mMapView = new MapView(this);
/* Now delegate the event to the MapView. */
this.mMapView.onCreate(pSavedInstanceState);
}
@Override
public final void onResume() {
super.onResume();
this.getMapView().onResume();
}
@Override
public final void onPause() {
super.onPause();
this.getMapView().onPause();
}
@Override
public final void onDestroy() {
super.onDestroy();
this.getMapView().onDestroy();
}
@Override
public final void onSaveInstanceState(final Bundle pSavedInstanceState) {
super.onSaveInstanceState(pSavedInstanceState);
this.getMapView().onSaveInstanceState(pSavedInstanceState);
}
@Override
public final void onLowMemory() {
super.onLowMemory();
this.getMapView().onLowMemory();
}
private final MapView getMapView() {
return this.mMapView;
}
}
A: The answer is no. It is not possible to utilize a MapView without extending MapActivity. As gulbrandr pointed out there is a similar question here, this may be of use for anyone attempting the same thing that I was. | unknown | |
d6967 | train | Will it just happily
deallocate/reuse/etc. activities
behind the scenes?
Yes.
Is there a way to cause the reusing of
activities so that only one instance
of each activity is ever allocated and
is just reused for each cycle?
Try FLAG_ACTIVITY_REORDER_TO_FRONT on your Intent to launch the activity. Based on the docs, it should give you your desired behavior.
Can one manipulate the activity stack
so that there aren't ~100
(approximated number of expected
cycles) cycles worth of activities on
the stack?
100? You must be expecting some very patient users.
Regardless, FLAG_ACTIVITY_REORDER_TO_FRONT should cover that too.
Can anyone suggest alternate
approaches to the cycles of activities
problem? I have considered view
flippers and tabs, but wasn't sure
that would be better or not.
Tabs aren't great for things where you're trying to enforce a flow, since tabs are designed for random (not sequential) access. ViewFlipper/ViewSwitcher could work, though then you have to manage BACK button functionality and make sure you're not effectively leaking memory within the activity, since you're expecting people to be using it for an extended period. | unknown | |
d6968 | train | Try downloading the module tar zip from cpan or metacpan. Then build the module locally using any make utility(e.g.dmake). You can find more info for building module locally from here. | unknown | |
d6969 | train | I think you are mistaken about the SWP_NOMOVE parameter. That parameter does not mean that the window will not be movable, it just means that the x,y parameters will be ignored during that specific call to the method SetWindowPos. The goal of that flag is to use the function SetWindowPos for changing the size of the target window without changing its position.
From SetWindowPos in MSDN:
SWP_NOMOVE
0x0002
Retains the current position (ignores X and Y parameters).
Something that you could try is to create a custom window on your application that handles all messages related to size and position (examples:WM_SIZE, WM_SIZING, WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING, etc) to prevent modifications, then set your excel window as a child window of your custom window.
You could also try to just remove the title bar | unknown | |
d6970 | train | Define an “outer” function that takes the self and the constant arguments. Inside that define an “inner” function that takes only the interactive arguments as parameters and can access self and the constant arguments from the outer scope.
from ipywidgets.widgets import interact
import matplotlib.pyplot as plt
DEFAULT_COLOR = 'r'
class Profile():
'''self.stages is a list of lists'''
stages = [[-1, 1, -1], [1, 2, 4], [1, 10, 100], [0, 1, 0], [1, 1, 1]]
def plot_stages(self, colour):
def _plot_stages(i):
plt.plot(self.stages[i], color=colour)
interact(_plot_stages, i=(0, 4, 1))
p = Profile()
p.plot_stages(DEFAULT_COLOR) | unknown | |
d6971 | train | couple of exemple :
int[] a={1,2,4,1}; output : 2 ==> if you can see (1+2= 3 ) ,(2+4=6) so those is %3=0 ==> beacuse that the number is 2 beacuse is two subarray that giving me %3 to be =0.
int[] a={3,4,4,2}; output : 2
int[] a={3,3,3,3,0,1}; output : 5
int[] a={3,2,7,6,6,1}; output : 5 | unknown | |
d6972 | train | About a general catch, not distinghuishing individual exceptions.
You can use base class exceptions, like IOException, and drop its child exceptions, like EOFException. This is a good practice as all (possibly future) child exceptions are catched. This principle also holds for a throws IOException clause.
Run time exceptions, when not treated in their own catch, should only be catched, maybe in the same way, as RuntimeException, when it is a catch-all. (One should not catch always all.) | unknown | |
d6973 | train | The assets directory is readonly. It's defined and initialized at compile time, you cannot add or edit its contents.
Source (note it doesn't mention anything about writing to files...only reading them.)
Use the SDCard for such operations.
A: slote is right . use internal file storage/SD Card or sqLite database to save image | unknown | |
d6974 | train | *
*If you want to sort Fruit, you need to implement the Comparable interface for the Fruit class.
*If you want to display attributes, have an abstract method in Fruit class and provide the implementations in the subclass.
This way depending on the instance of the Fruit , it will show the corresponding properties.
public abstract class Fruit implements Comparable{
public abstract void displayProperties();
@Override
public int compareTo(Fruit otherFruit){
return 0;
}
}
public class Banana extends Fruit {
private int seedCount;
@Override
public void displayProperties() {
// TODO Auto-generated method stub
System.out.println(seedCount);
}
}
public class Grape extends Fruit{
private String color;
@Override
public void displayProperties() {
// TODO Auto-generated method stub
System.out.println(color);
}
}
A: You could add an abstract method to Fruit displayProperties()
You would then be forced to impliment the method for all types of fruit, then in your for loop you would just call displayProperties()
A: This isn't recommended, but you could use
if(object instanceof Class) {
Class temp = (Class) object
//operate on object
}
But what you should do is create a Fruit interface that gives access to the important info related to all fruit, in general you shouldn't cast down to get extra information.
While downcasting isn't evil, it could mean you aren't taking full advantage of polymorphism. To take advantage of polymorphism one should ensure that the supertype the subtypes share has methods to get as much info or behavior as necessary.
For example, lets say you have a list of HousePets, and the HousePets consist of the subtypes Dog and Cat. You loop over this list and want to wag all of the tails of the HousePets that can wag their tails. For simplicity there are two ways to do this, either only the Dog has the method 'wagTail()' (since Cats don't wag tails), or HousePets has a method called 'wagTail()' that is inherited by Cats and Dogs (but the Cat's version does nothing). If we choose the first example the code would look something like this:
for(HousePet pet : petList)
if(pet instanceof Dog) {
((Dog)pet).wagTail();
}
And for the second example it would look like this:
for(HousePet pet : petList)
pet.wagTail();
The second example takes a little less code and is a little more streamlined. In the worst case scenario, if we go with the first option, we will need an if-block for each new subtype of HousePet, which will make the code bulkier/uglier/etc. Better yet we could have a HousePet method called "showHappiness", and the Dog would wag its tail while the cat purred.
A: I think you need an instanceof operator. It allows you to check object type.
if (list.get(0) instanceof Grape) {
// list.get(0) is Grape
} | unknown | |
d6975 | train | If you're trying to validate a string, it's simpler to do it as multiple checks.
m{^[A-Za-z0-9 /-]*\z} && /[A-Za-z]/ && /[0-9]/
Those can be combined into one pattern, but I advice against it.
m{^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9 /-]*\z}s
On the other hand, if you're trying to extract from a string, you'll need the following:
m{
[ /-]*+
(?: [A-Za-z] [A-Za-z /-]*+ [0-9]
| [0-9] [0-9 /-]*+ [A-Za-z]
)
[A-Za-z0-9 /-]*+
}x | unknown | |
d6976 | train | You can throw an exception:
throw "Help I have fallen and cannot get up";
Not exactly the same, but (in my experience) it's not too common to see exception handling in ordinary DOM-wrangling sorts of JavaScript code, so that usually will blow out of any event loop. However, it's not really the same thing as any surroundling try block will catch what you throw.
A: you mean terminate loop?
while(true) {
console.log()
if(condition) {break};
}
the break command exits the loop
but there is no kill or exit function in javascript.
A: Since JavaScript is event-based, a script doesn't control when it terminates — there's no die or exit.
If it's not one already, the best option is to refactor the code into a function that you can return from, or use a named block:
foo: {
// do work
break foo;
// not executed;
} | unknown | |
d6977 | train | Quick Primer to Passwords in the DB
This goes to show that encryption in the database is hard, and that you shouldn't do it unless you have thought carefully through your threat model and understand what all the tradeoffs are. To be honest, I have serious doubts that an ORM can ever give you the security you need where you need encryption (for important knowledge reasons), and on PostgreSQL, it is particularly hard because of the possibility of key disclosure in the log files. In general you really need to properly protect both encrypted and plain text with regard to passwords, so you really don't want a relational interface here but a functional one, with a query running under a totally different set of permissions.
Now, I can't tell in your example whether you are trying to protect passwords, but if you are, that's entirely the wrong way to go about it. My example below is going to use MD5. Now I am aware that MD5 is frowned upon by the crypto community because of the relatively short output, but it has the advantage in this case of not requiring pg_crypto to support and being likely stronger than attacking the password directly (in the context of short password strings, it is likely "good enough" particularly when combined with other measures).
Now what you want to do is this: you want to salt the password, then hash it, and then search the hashed value. The most performant way to do this would be to have a users table which does not include the password, but does include the salt, and a shadow table which includes the hashed password but not the user-accessible data. The shadow table would be restricted to its owner and that owner would have access to the user table too.
Then you could write a function like this:
CREATE OR REPLACE FUNCTION get_userid_by_password(in_username text, in_password text)
RETURNS INT LANGUAGE SQL AS
$$
SELECT user_id
FROM shadow
JOIN users ON users.id = shadow.user_id
WHERE users.username = $1 AND shadow.hashed_password = md5(users.salt || $2);
$$ SECURITY DEFINER;
ALTER FUNCTION get_userid_by_password(text, text) OWNER TO shadow_owner;
You would then have to drop to SQL to run this function (don't go through your ORM). However you could index shadow.hashed_password and have it work with an index here (because the matching hash could be generated before scanning the table), and you are reasonably protected against SQL injections giving away the password hashes. You still have to make sure that logging will not be generally enabled of these queries and there are a host of other things to consider, but it gives you an idea of how best to manage passwords per se. Alternatively in your ORM you could do something that would have a resulting SQL query like:
SELECT * FROM users WHERE id = get_userid_by_password($username, $password)
(The above is pseudocode and intended only for illustration purposes. If you use a raw query like that assembled as a text string you are asking for SQL injection.)
What if it isn't a password?
If you need reversible encryption, then you need to go further. Note that in the example above, the index could be used because I was searching merely for an equality on the encrypted data. Searching for an unencrypted data means that indexes are not usable. If you index the unencrypted data then why are you encrypting it in the first place? Also decryption does place burdens on the processor so it will be slow.
In all cases you need to carefully think through your threat model and ask how other vulnerabilities could make your passwords less secure. | unknown | |
d6978 | train | Magento calculates weight used for getting shipping rates in Mage_Sales_Model_Quote_Address_Total_Shipping::collect.
When collecting shipping address totals, items are looped and their weight accumulated and then set to address object.
That being said, you have to be careful how are you going to change this behavior. On a first look, it seems that using sales_quote_collect_totals_after event could be the right way.
When event is triggered get all shipping address items, loop through them and use custom logic for calculating weight.
Best of luck.
A: You writted event in adminhtml context, you have to change it to frontend. | unknown | |
d6979 | train | In solution one, I misunderstood something and find a horizontal line on the bounding box,
this is your desired line cordinates.
import numpy as np
import cv2
def get_order_points(pts):
# first - top-left,
# second - top-right
# third - bottom-right
# fourth - bottom-left
rect = np.zeros((4, 2), dtype="int")
# top-left point will have the smallest sum
# bottom-right point will have the largest sum
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
# top-right point will have the smallest difference
# bottom-left will have the largest difference
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
return rect
image = cv2.imread('image.png')
image = cv2.resize(image, (800, 800))
output_image = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
low = np.array([33, 91, 21])
high = np.array([253, 255, 255])
mask = cv2.inRange(HSV, low, high)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_contour = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)
# As I know there is 6 max contour we want I'm selecting 6 contour only to creating perfact mask
selected_contour = sorted_contour[:6]
blank_mask = np.zeros_like(mask)
mask = cv2.drawContours(blank_mask, selected_contour, -1, 255, -1)
cv2.imshow("mask", mask)
cv2.imwrite("mask.png", mask)
for i, cnt in enumerate(selected_contour):
# find min enclosing rect
commodity_rect = cv2.minAreaRect(cnt)
bounding_rect_points = np.array(cv2.boxPoints(commodity_rect), dtype=np.int)
cv2.drawContours(output_image, [bounding_rect_points], 0, (0, 255, 0), 2)
tl, tr, br, bl = get_order_points(bounding_rect_points)
left_point = (tl + bl) // 2
right_point = (tr + br) // 2
print(f"\nfor {i}th contour : ")
print("left_point : ", left_point)
print("right_point : ", right_point)
cv2.circle(output_image, tuple(left_point), 3, (255, 0, 0), -1)
cv2.circle(output_image, tuple(right_point), 3, (255, 0, 0), -1)
cv2.line(output_image, tuple(left_point), tuple(right_point), (0, 0, 255), 1)
cv2.imshow("output_image", output_image)
cv2.imwrite("output_image.png", output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
for 0th contour :
left_point : [606 597]
right_point : [785 622]
for 1th contour :
left_point : [ 64 236]
right_point : [214 236]
for 2th contour :
left_point : [325 201]
right_point : [507 295]
for 3th contour :
left_point : [ 56 638]
right_point : [244 619]
for 4th contour :
left_point : [359 574]
right_point : [504 625]
for 5th contour :
left_point : [605 241]
right_point : [753 241]
Output_Image:
A: This will help you to find your desired line coordinates. I have used the cv2.pointPolygonTest on contours point to find your desired points. more about cv2.pointPolygonTest here
import numpy as np
import cv2
image = cv2.imread('image.png')
image = cv2.resize(image, (800, 800))
output_image = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
low = np.array([33, 91, 21])
high = np.array([253, 255, 255])
mask = cv2.inRange(HSV, low, high)
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_contour = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)
# As I know there is 6 max contour we want I'm selecting 6 contour only to creating perfact mask
selected_contour = sorted_contour[:6]
blank_mask = np.zeros_like(mask)
mask = cv2.drawContours(blank_mask, selected_contour, -1, 255, -1)
cv2.imshow("mask", mask)
for i, cnt in enumerate(selected_contour):
# find min enclosing rect
commodity_rect = cv2.minAreaRect(cnt)
cv2.drawContours(output_image, [np.int0(cv2.boxPoints(commodity_rect))], 0, (0, 255, 0), 2)
# find center point of rect
M = cv2.moments(cnt)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.circle(output_image, (cX, cY), 5, (0, 255, 255), -1)
selceted_points = [[px, cY] for [[px, py]] in cnt if cv2.pointPolygonTest(cnt, (px, cY), measureDist=False) == 0]
left_point = min(selceted_points, key=lambda x: x[0])
right_point = max(selceted_points, key=lambda x: x[0])
print(f"\nfor {i}th contour : ")
print("left_point : ", left_point)
print("right_point : ", right_point)
cv2.circle(output_image, tuple(left_point), 3, (255, 0, 0), -1)
cv2.circle(output_image, tuple(right_point), 3, (255, 0, 0), -1)
cv2.line(output_image, tuple(left_point), tuple(right_point), (0, 0, 255), 1)
cv2.imshow("output_image", output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
for 0th contour :
left_point : [606, 613]
right_point : [786, 613]
for 1th contour :
left_point : [73, 233]
right_point : [211, 233]
for 2th contour :
left_point : [329, 248]
right_point : [501, 248]
for 3th contour :
left_point : [58, 637]
right_point : [246, 637]
for 4th contour :
left_point : [364, 600]
right_point : [508, 600]
for 5th contour :
left_point : [605, 237]
right_point : [753, 237]
Mask Image:
Output Image:
A: have you tried something like this:
commodity_rect = cv2.minAreaRect(commodity_contour) #Find the minAreaRect for each contour
minAxis = round(min(commodity_rect[1])) #Find minor axis size
maxAxis = round(max(commodity_rect[1])) #Find major axis size
but instead of minAreaRect, what I think you're looking for is the rotating caliper algorithm. Take a look at the link below:
https://chadrick-kwag.net/python-implementation-of-rotating-caliper-algorithm/#:~:text=Rotating%20caliper%20algorithm%20is%20used,all%20possible%20rotating%20caliper%20rectangles. | unknown | |
d6980 | train | You have to set the 'employee' field in your Address class.
Update the setter in your Employee class to:
public void setAddresses(List<Address> addresses) {
this.addresses.clear();
for (Address address: addresses) {
address.setEmployee(this);
this.addresses.add(address);
}
}
A: Before saving the Employee object, All address objects has to set the employ reference so then hibernate can populate empId in address tale.
@Autowired
private SessionFactory sessionFactory;
public Employee save(Employee employee) {
Session session = getSession();
for(Address address: employee.getAddresses()){
address.setEmployee(employee); //Set employee to address.
}
session.persist(employee);
return employee;
}
private Session getSession() {
return sessionFactory.getCurrentSession();
} | unknown | |
d6981 | train | I'm not an expert in Javascript, so I may be talking nonsense.
It seems like you can achieve what you want if your struct S implements the Codable protocol. Then you can transform it to a Data blob using an encoder, like this:
let encoder = JSONEncoder()
do {
let data = try encoder.encode(s)
// do what you want with the blob
} catch {
// handle error
}
And back to S, like this:
let decoder = JSONDecoder()
do {
let s = try decoder.decode(S.self, from: data)
} catch {
// handle error
}
If S is Codable, [S] (an Array<S>) will also be Codable.
You can probably pass the data to your scriptas a String, then you'll have to transform your data do string with JSONSerialization | unknown | |
d6982 | train | Click on the Filtering icon at the top right corner of the global search dialog. It seems it remembers the filters. | unknown | |
d6983 | train | From http://www.w3.org/TR/css3-lists/#html4:
/* The start attribute on ol elements */
ol[start] {
counter-reset: list-item attr(start, integer, 1);
counter-increment: list-item -1;
}
Adding this to the CSS allowed the start attribute to be recognized in my tests.
EDIT:
Instead of using the start attribute, you can use CSS classes for each new starting point. The downside is that this will require more maintenance should you need to change anything.
CSS:
ol.start4
{
counter-reset: item 4;
counter-increment: item -1;
}
ol.start6
{
counter-reset: item 6;
counter-increment: item -1;
}
HTML:
<div>
<ol>
<li>Item 1</li>
<li>Item 2
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol></li>
<li>Item 3
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol></li>
</ol>
</div>
<div>
<ol class="start4">
<li>Item 4
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol></li>
<li>Item 5</li>
</ol>
</div>
<div>
<ol class="start6">
<li>Item 6</li>
<li>Item 7
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol></li>
</ol>
</div>
A: Just remove the css, and correctly close and reopen <ol> tags.
If you need to split the list in two separate tabs, you have to close the first <ol> inside the first tab. Then, reopen the new list with the start parameter inside the second tab: <ol start="3">.
Working fiddle - (I set start="5" to show it's working; for your purposes, just set it to 3 or what you need)
UPDATE:
Keep the CSS, and wrap all the tabs in the main <ol> and </ol>, so the counter doesn't reset.
http://jsfiddle.net/qGCUk/227/ | unknown | |
d6984 | train | It might be to do with the context.
I've had issues in the past with getApplicationContext not working for certain things, although can't remember what form the top of my head.
Instead of using getApplicationContext, in the activity where you call your async task put this in the constructor call. For example, assuming you are going from MainActivity change the line new test().execute(); to new test(MainActivity.this).execute();
Then in the async class create the constructor as
public test(Context context) and set a global class variable to be the value of context, and then use this in your toast.makeText instead of what is returned from getApplicationContext.
Also take a look in the logcat, see if there are any errors or exceptions being thrown, it might also be worth adding a log line in the onpostexecute method just to double check you're definetely going in there.
A: Create a constructor in the test class which receive a context and use that context in the Toast.makeText. Pass the host activity context to that constructor.
getApplicationContext() is a Context class method, AsyncTask does not inherent from that class. I suppose you are in a scope where you can invoke that method but that scope context is not valid in the scope that you are invoking the Toast.makeText method. | unknown | |
d6985 | train | well! well!
I was able to do it using following line:
Split-Path (Split-path $MyInvocation.InvocationName -Parent) | unknown | |
d6986 | train | The following may not be a direct answer but a close one?
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
At least it may be inspiring.
A: REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).
IF "%time:~0,1%" LSS "1" (
SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)
ECHO %DATETIME%
A: I usually do it this way whenever I need a date/time string:
set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%
This is for the German date/time format (dd.mm.yyyy hh:mm:ss). Basically I concatenate the substrings and finally replace all spaces with zeros.
The resulting string has the format: yyyy_mm_dd__hh_mm_ss
Short explanation of how substrings work:
%VARIABLE:~num_chars_to_skip,num_chars_to_keep%
So to get just the year from a date like "29.03.2018" use:
%DATE:~6,4%
^-----skip 6 characters
^---keep 4 characters
A: Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):
@ECHO OFF
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error
:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto s_done
Set _yyyy=%%L
Set _mm=00%%J
Set _dd=00%%G
Set _hour=00%%H
SET _minute=00%%I
SET _second=00%%K
)
:s_done
:: Pad digits with leading zeros
Set _mm=%_mm:~-2%
Set _dd=%_dd:~-2%
Set _hour=%_hour:~-2%
Set _minute=%_minute:~-2%
Set _second=%_second:~-2%
Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump
:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_
:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...
A: @ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention ('YYYYMMDD_HHMMSS')
: Scrapes the characters out of their expected permissions in the date/time
: environment variables.
: Expects a date format of '____MM_DD_YYYY'
: Expects a time format of 'HH:MM:SS' or ' H:MM:SS'
SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)
ECHO %dtStamp%
PAUSE
A: The offset:length formatting supported with the SET command in Windows will not allow you to pad the 0 as you seem to be interested in.
However, you can code a BATCH script to check for the hour being less than 10 and
pad accordingly with a different echo string.
You will find some information on the SET command on this link.
You can also change to other programming methods to get here.
It is quite simple in unix bash (available with Cygwin on Windows) to just say,
date +%Y_%m_%d__%H_%M_%S
And, it always pads correctly.
A: I did it this way:
REM Generate FileName from date and time in format YYYYMMTTHHMM
Time /T > Time.dat
set /P ftime= < Time.dat
set FileName=LogFile%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%.log
echo %FileName%
LogFile201310170928.log
A: I'm really new to batch files and this is my code!! (I am not sure why, but I couldn't combine date /t and time /t together and I couldn't use %date% and %time% directly without a variable...)
@ECHO OFF
set ldt=%date% %time%
echo %ldt%>> logs.txt
EXIT
It is kind of reused from others (the question was to get a formatted timedate to use as filename).
A: ::========================================================================
::== CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS
::======= ================================================================
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DATETIME=%DTS:~0,8%-%DTS:~8,6%
The first line always outputs in this format regardles of timezone:
20150515150941.077000+120
This leaves you with just formatting the output to fit your wishes.
A: If PowerShell is installed, then you can easily and reliably get the Date/Time in any format you'd like, for example:
for /f %%a in ('powershell -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a
move "%oldfile%" "backup-%datetime%"
Of course nowadays PowerShell is always installed, but on Windows XP you'll probably only want to use this technique if your batch script is being used in a known environment where you know PS is available (or check in your batch file if PowerShell is available...)
You may reasonably ask: why use a batch file at all if you can use PowerShell to get the date/time, but I think some obvious reasons are: (a) you're not all that familiar with PowerShell and still prefer to do most things the old-fashioned way with batch files or (b) you're updating an old script and don't want to port the whole thing to PS.
A: This batch script will do exactly what the O.P. wants (tested on Windows XP SP3).
I also used that clever registry trick described by "jph" previously which IMHO is the simplest way of getting 100% consistent formatting of the date to "yyyy_MM_dd" on any Windows system new or old. The change to one Registry value for doing this is instantaneous temporary and trivial; it only lasts a few milliseconds before it is immediately reverted back.
Double-click this batch file for an instant demo, Command Prompt window will pop up and display your timestamp . . . . .
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A
:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul
SET MYDATE=%date%
:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul
:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)
:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2%
:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT,
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)
:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%
:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO Your timestamp is: %TIMESTAMP%
ECHO.
ECHO.
ECHO Job is done. Press any key to exit . . .
PAUSE > NUL
EXIT
A: There is another easy way of doing it:
set HH=%time:~0,2%
if %HH% LEQ 9 (
set HH=%time:~1,1%
)
A: This bat file (save as datetimestr.bat) produces the datetime string 3 times: (1) long datetime string with day of week and seconds,
(2) short datetime string without them and
(3) short version of the code.
@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%
set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to
REM replace semi-colons with hyphens (or any
REM non-special character)
set t=%t::=%
set t=%t:.=%
set datetimestr=%d%_%t%
@echo Long date time str = %datetimestr%
set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%
@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%
pause
To give proper credit, I merged the concepts from Peter Mortensen (Jun 18 '14 at 21:02) and opello (Aug 25 '11 at 14:27).
You can write this much shorter, but this long version makes reading and understanding the code easy.
A: I came across this problem today and solved it with:
SET LOGTIME=%TIME: =0%
It replaces spaces with 0s and basically zero-pads the hour.
After some quick searching I didn't find out if it required command extensions (still worked with SETLOCAL DISABLEEXTENSIONS).
A: To generate a YYYY-MM-DD hh:mm:ss (24-hour) timestamp I use:
SET CURRENTTIME=%TIME%
IF "%CURRENTTIME:~0,1%"==" " (SET CURRENTTIME=0%CURRENTTIME:~1%)
FOR /F "tokens=2-4 delims=/ " %%A IN ('DATE /T') DO (SET TIMESTAMP=%%C-%%A-%%B %CURRENTTIME%)
A: I like the short version on top of @The lorax,
but for other language settings it might be slightly different.
For example, in german language settings (with natural date format: dd.mm.yyyy) the month query has to be altered from 4,2 to 3,2:
@ECHO OFF
: Sets the proper date and time stamp with 24h time for log file naming convention i.e.
SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~3,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~3,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)
ECHO %dtStamp%
: Outputs= 20160727_081040
: (format: YYYYMMDD_HHmmss; e.g.: the date-output of this post timestamp)
PAUSE
A: As has been noted, parsing the date and time is only useful if you know the format being used by the current user (for example, MM/dd/yy or dd-MM-yyyy just to name two). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.
You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.
There are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.
Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.
reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f
A: This is my 2 cents for adatetime string. On MM DD YYYY systems switch the first and second %DATE:~ entries.
REM ====================================================================================
REM CREATE UNIQUE DATETIME STRING FOR ADDING TO FILENAME
REM ====================================================================================
REM Can handle dd DDxMMxYYYY and DDxMMxYYYY > CREATES YYYYMMDDHHMMSS (x= any character)
REM ====================================================================================
REM CHECK for SHORTDATE dd DDxMMxYYYY
IF "%DATE:~0,1%" GTR "3" (
SET DATETIME=%DATE:~9,4%%DATE:~6,2%%DATE:~3,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
) ELSE (
REM ASSUMES SHORTDATE DDxMMxYYYY
SET DATETIME=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
)
REM CORRECT FOR HOURS BELOW 10
IF %DATETIME:~8,2% LSS 10 SET DATETIME=%DATETIME:~0,8%0%DATETIME:~9,5%
ECHO %DATETIME%
A: set hourstr = %time:~0,2%
if "%time:~0,1%"==" " (set hourstr=0%time:~1,1%)
set datetimestr=%date:~0,4%%date:~5,2%%date:~8,2%-%hourstr%%time:~3,2%%time:~6,2%
A: Create a file called "search_files.bat" and place the contents below into the file. Then double click it. The temporary %THH% variable was put in place to handle the AM appropriately. If there is a 0 in the first 2 digits of the time, Windows ignores the rest of the file name of the LOG file.
CD .
SET THH=%time:~0,2%
SET THH=%THH: =0%
dir /s /b *.* > %date:~10,4%-%date:~4,2%-%date:~7,2%@%THH%.%time:~3,2%.%time:~6,2%.LOG
A: You may use these...
Parameters:
%date:~4,2% -- month
%date:~7,2% -- days
%date:~10,4% -- years
%time:~1,1% -- hours
%time:~3,2% -- minutes
%time:~6,2% -- seconds
%time:~9,2% -- mili-seconds
%date:~4,2%%date:~7,2%%date:~10,4% : MMDDYYYY
%date:~7,2%%date:~4,2%%date:~10,4% : DDMMYYYY
%date:~10,4%%date:~4,2%%date:~7,2% : YYYYMMDD
A: I ended up with this script:
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%
set year=%date:~-4%
echo year=%year%
:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%
set datetimef=%year%%month%%day%_%hour%%min%%secs%
echo datetimef=%datetimef%
A: If you don't exactly need this format:
2009_07_28__08_36_01
Then you could use the following 3 lines of code which uses %date% and %time%:
set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%
Note: The characters / and : are removed and the character . and space is replaced with an underscore.
Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):
echo %mytimestamp%
Wed_08052015_124950_93
A: I tried the accepted answer and it works pretty well. Unfortunately the US Time Format appears to be H:MM:SS.CS, and the missing 0 on the front was causing parsing problems before 10 am. To get over this hurdle and also allow parsing of most any of the world time formats, I came up with this simple routine that appears to work quite well.
:ParseTime
rem The format of %%TIME%% is H:MM:SS.CS or (HH:MM:SS,CS) for example 0:01:23.45 or 23:59:59,99
FOR /F "tokens=1,2,3,4 delims=:.," %%a IN ("%1") DO SET /A "%2=(%%a * 360000) + (%%b * 6000) + (%%c * 100) + %%d"
GOTO :EOF
The nice thing with this routine is that you pass in the time string as the first parameter and the name of the environment variable you want to contain the time (in centiseconds) as the second parameter. For example:
CALL :ParseTime %START_TIME% START_CS
CALL :ParseTime %TIME% END_CS
SET /A DURATION=%END_CS% - %START_CS%
(*Chris*)
A: Maybe something like this:
@call:DateTime
@for %%? in (
"Year :Y"
"Month :M"
"Day :D"
"Hour :H"
"Minutes:I"
"Seconds:S"
) do @for /f "tokens=1-2 delims=:" %%# in (%%?) do @for /f "delims=" %%_ in ('echo %%_DT_%%$_%%') do @echo %%# : _DT_%%$_ : %%_
:: OUTPUT
:: Year : _DT_Y_ : 2014
:: Month : _DT_M_ : 12
:: Day : _DT_D_ : 17
:: Hour : _DT_H_ : 09
:: Minutes : _DT_I_ : 04
:: Seconds : _DT_S_ : 35
@pause>nul
@goto:eof
:DateTime
@verify errorlevel 2>nul & @wmics Alias /? >nul 2>&1
@if not errorlevel 1 (
@for /f "skip=1 tokens=1-6" %%a in ('wmic path win32_localtime get day^,hour^,minute^,month^,second^,year /format:table') do @if not "%%f"=="" ( set "_DT_D_=%%a" & set "_DT_H_=%%b" & set "_DT_I_=%%c" & set "_DT_M_=%%d" & set "_DT_S_=%%e" & set "_DT_Y_=%%f" )
) else (
@set "_DT_T_=1234567890 "
)
@if errorlevel 1 (
@for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "Y" "M" "D" "H" "I" "S") do @set "_DT_%%~?_=%%~?"
@for %%? in ("Date" "Time") do @for /f "skip=2 tokens=1,3" %%a in ('reg query "HKCU\Control Panel\International" /v ?%%~? 2^>nul') do @for /f %%x in ('echo:%%_DT_%%a_%%') do @if "%%x"=="%%a" set "_DT_%%a_=%%b"
@for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_T_=%%a%%b%%c"
)
@if errorlevel 1 (
@if "%_DT_iDate_%"=="0" (set "_DT_F_=_DT_D_ _DT_Y_ _DT_M_") else if "%_DT_iDate_%"=="1" (set "_DT_F_=_DT_D_ _DT_M_ _DT_Y_") else if "%_DT_iDate_%"=="2" (set "_DT_F_=_DT_Y_ _DT_M_ _DT_D_")
@for /f "tokens=1-4* delims=%_DT_sDate_%" %%a in ('date/t') do @for /f "tokens=1-3" %%x in ('echo:%%_DT_F_%%') do @set "%%x=%%a" & set "%%y=%%b" & set "%%z=%%c"
@for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_H_=%%a" & set "_DT_I_=%%b" & set "_DT_S_=%%c"
@for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "T") do @set "_DT_%%~?_="
)
@for %%i in ("Y" ) do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+= 0 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-4%%"') do @set "_DT_%%~i_=%%~k"
@for %%i in ("M" "D" "H" "I" "S") do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=100 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-2%%"') do @set "_DT_%%~i_=%%~k"
@exit/b
A: Use REG to save/modify/restore what ever values are most useful for your bat file. This is windows 7, for other versions you may need a different key name.
reg save "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg /y
reg add "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate /d "yyyy-MM-dd" /f
set file=%DATE%-%TIME: =0%
reg restore "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg
set file=%file::=-%
set file=%file:.=-%
set file
A: In situations like this use a simple, standard programming approach:
Instead of expending a huge effort parsing an unknown entity, simply save the current configuration, reset it to a known state, extract the info and then restore the original state. Use only standard Windows resources.
Specifically, the date and time formats are stored under the registry key
HKCU\Control Panel\International\ in [MS definition] "values": "sTimeFormat" and "sShortDate".
Reg is the console registry editor included with all Windows versions.
Elevated privileges are not required to modify the HKCU key
Prompt $N:$D $T$G
::Save current config to a temporary (unique name) subkey, Exit if copy fails
Set DateTime=
Set ran=%Random%
Reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp%ran%" /f
If ErrorLevel 1 GoTO :EOF
::Reset the date format to your desired output format (take effect immediately)
::Resetting the time format is useless as it only affect subsequent console windows
::Reg add "HKCU\Control Panel\International" /v sTimeFormat /d "HH_mm_ss" /f
Reg add "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f
::Concatenate the time and (reformatted) date strings, replace any embedded blanks with zeros
Set DateTime=%date%__%time:~0,2%_%time:~3,2%_%time:~6,2%
Set DateTime=%DateTime: =0%
::Restore the original config and delete the temp subkey, Exit if restore fails
Reg copy "HKCU\Control Panel\International-Temp%ran%" "HKCU\Control Panel\International" /f
If ErrorLevel 1 GoTO :EOF
Reg delete "HKCU\Control Panel\International-Temp%ran%" /f
Simple, straightforward and should work for all regions.
For reasons I don't understand, resetting the "sShortDate" value takes effect immediately in
a console window but resetting the very similar "sTimeFormat" value does NOT take effect
until a new console window is opened. However, the only thing changeable is the delimiter -
the digit positions are fixed.Likewise the "HH" time token is supposed to prepend leading zeros but it doesn't.
Fortunately, the workarounds are easy.
A: Using % you will run into a hex operation error when the time value is 7-9. To avoid this, use DelayedExpansion and grab time values with !min:~1!
An alternate method, if you have PowerShell is to call that:
for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)
A: This script use a WMI interface accessed primary via WMIC tool, which is an integral part of Windows since Windows XP Professional (Home edition is supported too, but the tool is not installed by default). The script also implements a workaround of missing WMIC tool by creating and calling a WSH vbscript for access a WMI interface and write to console output the time with same format as WMIC tool provide.
@ECHO OFF
REM Returns: RETURN
REM Modify: RETURN, StdOut
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM YYYY = 4-digit year
REM MM = 2-digit month
REM DD = 2-digit day
REM hh = 2-digit hour
REM mm = 2-digit minute
REM ss = 2-digit second
REM ms = 3-digit millisecond
CALL :getTime %*
ECHO %RETURN%
GOTO :EOF
REM SUBROUTINE
REM Returns: RETURN
REM Modify: RETURN
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM YYYY = 4-digit year
REM MM = 2-digit month
REM DD = 2-digit day
REM hh = 2-digit hour
REM mm = 2-digit minute
REM ss = 2-digit second
REM ms = 3-digit millisecond
:getTime
SETLOCAL EnableDelayedExpansion
SET DELIM=-
WHERE /Q wmic.exe
IF NOT ERRORLEVEL 1 FOR /F "usebackq skip=1 tokens=*" %%x IN (`wmic.exe os get LocalDateTime`) DO (SET DT=%%x & GOTO getTime_Parse)
SET _TMP=%TEMP:"=%
ECHO Wscript.StdOut.WriteLine (GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@").LocalDateTime)>"%_TMP%\get_time_local-helper.vbs"
FOR /F "usebackq tokens=*" %%x IN (`cscript //B //NoLogo "%_TMP%\get_time_local-helper.vbs"`) DO (SET DT=%%x & GOTO getTime_Parse)
:getTime_Parse
SET _RET=
IF "%1" EQU "" (
SET _RET=%DT:~0,4%%DELIM%%DT:~4,2%%DELIM%%DT:~6,2%%DELIM%%DT:~8,2%%DELIM%%DT:~10,2%%DELIM%%DT:~12,2%%DELIM%%DT:~15,3%
) ELSE (
REM Not recognized format strings are ignored during parsing - no error is reported.
:getTime_ParseLoop
SET _VAL=
IF "%1" EQU "YYYY" SET _VAL=%DT:~0,4%
IF "%1" EQU "MM" SET _VAL=%DT:~4,2%
IF "%1" EQU "DD" SET _VAL=%DT:~6,2%
IF "%1" EQU "hh" SET _VAL=%DT:~8,2%
IF "%1" EQU "mm" SET _VAL=%DT:~10,2%
IF "%1" EQU "ss" SET _VAL=%DT:~12,2%
IF "%1" EQU "ms" SET _VAL=%DT:~15,3%
IF DEFINED _VAL (
IF DEFINED _RET (
SET _RET=!_RET!%DELIM%!_VAL!
) ELSE (
SET _RET=!_VAL!
)
)
SHIFT
IF "%1" NEQ "" GOTO getTime_ParseLoop
)
ENDLOCAL & SET RETURN=%_RET%
GOTO :EOF
A: A nice single-line trick to avoid early variable expansion is to use cmd /c echo ^%time^%
cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%
A: So the problem with %DATE% is that it depends on locale. So most of the previous answers did not work for me. If you are not picky about the exact format and just want a timestamp to differentiate the files you can do this:
set _date=%DATE%-%TIME%
set _date=%_date:/=-%
set _date=%_date: =-%
set _date=%_date::=-%
set _date=%_date:.=-%
echo %_date%
This should work for most locales. If it doesn't add another line set _date=%_date:<offending_char>=-% to remove the offending character. ie: a character which is not compatible with filenames or something you don't want in the file name.
Please note this doesn't meet the exact criteria laid down by the question.
A: :: =============================================================
:: Batch file to display Date and Time seprated by undescore.
:: =============================================================
:: Read the system date.
:: =============================================================
@SET MyDate=%DATE%
@SET MyDate=%MyDate:/=:%
@SET MyDate=%MyDate:-=:%
@SET MyDate=%MyDate: =:%
@SET MyDate=%MyDate:\=:%
@SET MyDate=%MyDate::=_%
:: =============================================================
:: Read the system time.
:: =============================================================
@SET MyTime=%TIME%
@SET MyTime=%MyTime: =0%
@SET MyTime=%MyTime:.=:%
@SET MyTime=%MyTime::=_%
:: =============================================================
:: Build the DateTime string.
:: =============================================================
@SET DateTime=%MyDate%_%MyTime%
:: =============================================================
:: Display the Date and Time as it is now.
:: =============================================================
@ECHO MyDate="%MyDate%" MyTime="%MyTime%" DateTime="%DateTime%"
:: =============================================================
:: Wait before close.
:: =============================================================
@PAUSE
:: =============================================================
A: Split the results of the date command by slash, then you can move each of the tokens into the appropriate variables.
FOR /F "tokens=1-3 delims=/" %%a IN ("%date:~4%") DO (
SET _Month=%%a
SET _Day=%%b
SET _Year=%%c
)
ECHO Month %_Month%
ECHO Day %_Day%
ECHO Year %_Year%
A: For a very simple solution for numeric date for use in filenames use the following code:
set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%
rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt
A: *
*set xtime=%time%
*if "%xtime:~0,1%" == " " set xtime=0%xtime:~1,7%
*set isodate=%date:~-4%%date:~3,2%%date:~0,2%_%xtime:~0,2%%xtime:~3,2%%time:~6,2%
A: Hope this helps:
set MM=%date:~4,2%
set DD=%date:~7,2%
set YYYY=%date:~10,4%
echo %DD%_%MM%_%YYYY%
This will print 05_06_2021
A: for /f "tokens=1-4 delims=/ " %%I in ("%DATE%") do set curdate=%%K_%%J_%%I
for /f "tokens=1-4 delims=:," %%I in ("%TIME: =0%") do set curtime=%%I_%%J_%%K
echo %curdate%__%curtime%
replace delims symbols if your system uses another (used for slicing to %%I,%%J...)
also edit curdate if your system uses another D/M/Y order | unknown | |
d6987 | train | I'm an idiot. I was doing hash_object = hashlib.sha1(pKey), but pKey is an RSA key, not a string, so I needed to do hash_object = hashlib.sha1(pKey.exportKey()) instead. | unknown | |
d6988 | train | inside GeoTagTask location object is different one and also doesn't initilized.
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
A: Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
Location location;
void onCreate() {
....
location = locationManager.getLastKnownLocation(provider);
....
}
}
Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
...
} | unknown | |
d6989 | train | Ok i managed to resolve my problem.
First i used StringBuilder instead of IntPtr.
To add a string "COR_ENABLE_PROFILING=1\0COR_PROFILER=PROFILER_GUID\0COR_PROFILER_PATH=GetProfilerFullPat\0\0"
i simply add("COR_ENABLE_PROFILING=1") and the increse the Stringbuilder lenght + 1 etc...;
the end should be incremented one more time lenght++ (this is the ansi encoding);
Second thing is to change and add marshalling into the imported method
Instead of [In] IntPtr lpEnvironment add [In, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpEnvironment
A: There's no need to use P/Invoke for this, you can use the .Net Process.Start method directly from your C# code.
If you want to customize the process startup, pass environment variables etc, use one of the overloads that takes a ProcessStartInfo object. | unknown | |
d6990 | train | If we use self-hosted agent, we need to configure the environment on the local machine. According to the error message, It seems that your agent machine do not have the .NETFramework 4.7.2, we should Install the .NET Framework 4.7.2 and restart the agent.
A: It looks like I had to add some specificity to publish command with the projects argument. I put the Web API project path here and the build now works. I guess it was trying to publish both the Web API and WPF projects.
Anymore insights? | unknown | |
d6991 | train | According to MySQL doc the syntax should be :
INSERT IGNORE INTO messages (message, hash, date_add)
VALUES('message', 'hash', NOW()); | unknown | |
d6992 | train | Consider using the unscanned_table_summary.sql query we provide on GitHub | unknown | |
d6993 | train | It's quite hard to understand your question, but I'll have a shot:
The source code in Angular projects is composed of ES modules, ie functions and variables are passed from one file to another via imports and exports.
If you want to use val from test.js in some.component.ts, you might want to do that:
In test.js:
var val = /* ... */
export { val }
In some.component.ts:
import { val } from './test.js';
@Component({...})
export class SomeComponent {
ngOnInit() {
val.launch();
}
} | unknown | |
d6994 | train | You need to enable imap in your php.ini.
I used the wamp menu to edit the php.ini. I enabled the php_imap.dll.
-> http://www.wampserver.com/phorum/read.php?2,23447,printview,page=1
A: I got the solution:
I am running Windows 7 64bit environment with WAMP server, it has two php.ini files:
1] C:\wamp\bin\apache\apache2.2.22\bin
Enable php_imap.dll extension by removing ; at beginning of string
2] C:\wamp\bin\php\php5.3.13
Enable php_imap.dll extension by removing ; at beginning of string
And it works now ! | unknown | |
d6995 | train | Access to a remote Service Control Manager (SCM) is subject to OS privileges. W/o SCM privileges you cannot know what services are running, nor can you start or stop any. The required privileges are listed at Access Rights for the Service Control Manager.
None of the above is in any way at all related to SQL Server security. Services are controlled by SCM, not SQL Server. | unknown | |
d6996 | train | [...]
uses
activex, objcomauto, comobj;
type
{$METHODINFO ON}
TMySriptableClass = class(TObjectDispatch)
public
[...]
function FnWithVarNumOfArgs(const args: OleVariant): string;
[...]
function TMySriptableClass.FnWithVarNumOfArgs(const args: OleVariant): string;
var
dispParams: activex.DISPPARAMS;
vtRet, Element: OleVariant;
Enum: IEnumVARIANT;
Fetched: LongWord;
begin
if TVarData(args).VType = varDispatch then begin
OleCheck(IDispatch(args).Invoke(DISPID_NEWENUM, GUID_NULL,
LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
dispParams, @vtRet, nil, nil));
Enum := IUnknown(vtRet) as IEnumVARIANT;
while (Enum.Next(1, Element, Fetched) = S_OK) do
ShowMessage(Element);
end;
Result := 'OK';
end;
[...]
ASW.Execute('var myArray=["myarg1", 5, true];' +
'MyObj.FnWithVarNumOfArgs(myArray);');
[...]
A: The way you have set it up now, you would need to pass in an array of string since you declared the parameter as such. In Delphi itself that could be done using
MyObj.FnWithVarNumOfArgs(Array("1","2","3"))
Which would create a dynamic arry with the given values and then pass it to FnWithVarNumOfArgs.
From a scripting language Delphi's Array function certainly won't be available and you would need to do something clever with pointers, and I have no clue whether you could even get that to work.
Possibly your best bet is to use what is known as Variant Open Array Parameters.
From the help: http://docwiki.embarcadero.com/RADStudio/en/Parameters_(Delphi)#Variant_Open_Array_Parameters
Variant open array parameters allow
you to pass an array of differently
typed expressions to a single
procedure or function. To define a
routine with a variant open array
parameter, specify array of const as
the parameter's type. Thus
procedure DoSomething(A: array of
const);
declares a procedure called
DoSomething that can operate on
heterogeneous arrays.
The array of const construction is
equivalent to array ofTVarRec.
TVarRec, declared in the System unit,
represents a record with a variant
part that can hold values of integer,
Boolean, character, real, string,
pointer, class, class reference,
interface, and variant types.
TVarRec's VType field indicates the
type of each element in the array.
Some types are passed as pointers
rather than values; in particular,
strings are passed as Pointer and must
be typecast to string. | unknown | |
d6997 | train | What would need to be done to code the program to use both processors?
You need to understand how the code is spending the cpu-cycles, i.e. benchmark. Read on about simple method duration versus context-switch duration.
"C++ has no notion of cores". Thus, the idea of associating a thread with a particular core is delegated to the operating system (in which the program is executing), and I have not seen the C++ language semantics for the issue. I have read of os calls to associate a thread with a core, but I have never grokked why, nor experimented.
On Ubuntu, I simply start the threads, and rely on the OS (Linux) to assign each running thread to an available processor resource. Linux seems to do a reasonable job.
I have measure two threads to perform the 'same' comparison work on two independent data's to cut the duration in half, and both cores are often fully utilized. (small to no i/o actions mixed in)
Contexts switches are about an order of magnitude slower than method invocations. So perhaps your code design should avoid switching.
Or, perhaps it is an effort of balance, code granularity, i.e. how much code to finish for each switch.
On my Ubuntu 17.10 system I have measured the combined duration of '::sem_wait()' and '::sem_post()' (both small methods) to about 31 ns (103.7 M events in 3,237,099 us), [with no context switches, of course].
On my 2 core processor, one of my tests runs 10 threads for 10 seconds, and does not force a context switch, leaving a single critical section for the thread-to-thread interaction. I was surprised that the same thread often runs multiple times before one of the 'starving' threads gets to run (it is not a problem on that 'Linux minor benchmark' - lmbm). The code reports 297 ns per context switch. (33 M switches in 10 secs, 297 ns per).
When I enforce a 'balanced-sharing-of-cores' (by using two semaphores per thread), every thread runs as often as any other. The switch duration is quite a bit longer (but not available to me at this moment).
I don't have the opportunity to measure 10 threads on 44 cores, it sounds like fun. I estimate the range of performance would be 'big' - perhaps from "stalled" to "10x" the duration of 1 thread. Depending not on which core the code runs on, but on what the code does when it runs. | unknown | |
d6998 | train | To elaborate my suggestion in the comments, I would implement the following algorithm for spending points:
*
*Find the oldest still valid rows (say A and B) with a sum equal or larger than the required amount (X). How to select rows that sum to a certain value
*If such rows do not exist, return an error.
*Mark rows A and B as "spent"
*Calculate the remaining points (C = A + B - X)
*If C == 0 go to the end
*Find max expiration date (D) between A and B
*Create a new row with expiration date D and amount C.
*The end
Make sure to wrap all database calls into one transaction, or you could create a room for weird bugs and exploits. | unknown | |
d6999 | train | This is allocating huge amounts of (wasted) memory.
Since you can use decimal floating numbers to represent this number without any loss of precision, I'd do that:
Note that 1 << n is equal to 2^n (pow(2, n)), so you can write:
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
namespace bmp = boost::multiprecision;
using number = bmp::number<bmp::cpp_dec_float<50, intmax_t> >;
int main() {
int64_t a = 0xffffffff;
std::cout << pow(number(2), a) << std::endl;
}
Which gets the correct
1.55164e+1292913986
You can verify it is correct:
for (intmax_t const a : { -8888ll, 0xFFFFll, 0xFFFFFFFFll, }) {
std::cout << pow(number(2), a) << std::endl;
auto roundtrip_exponent = bmp::log2(pow(number(2), a));
auto reverse = round(roundtrip_exponent).convert_to<intmax_t>();
std::cout << "Reverse: " << std::hex << std::showbase << reverse << std::dec << "\n";
std::cout << "Match: " << std::boolalpha << (a == reverse) << "\n";
}
Prints Live On Coliru
2.78868e-2676
Reverse: 0xffffffffffffdd48
Match: true
1.00176e+19728
Reverse: 0xffff
Match: true
1.55164e+1292913986
Reverse: 0xffffffff
Match: true
You'll inevitably lose some precision on the inexact operations (log2) in the extreme cases.
If you're curious you may want to try to print the full precision by setting std::fixed:
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
namespace bmp = boost::multiprecision;
using number = bmp::number<bmp::cpp_dec_float<50, intmax_t> >;
int main() {
std::cout << std::fixed << pow(number(2), 0xFFFFFFFFll) << std::endl;
}
Redirect the output to a file! It's gonna write 1.3GiB in decimal digits. This should explain why it didn't work too well with the arbitrary precision integer representation.
All of the output compresses to:
0000000 3531 3135 3436 3230 3137 3339 3631 3334
0000020 3730 3130 3934 3439 3535 3737 3339 3831
0000040 3232 3937 3535 3631 3334 3936 3939 3038
0000060 3737 3938 3631 3338 3737 3030 3532 3339
0000100 3533 3538 3636 3230 3935 3039 3030 3030
0000120 3030 3030 3030 3030 3030 3030 3030 3030
*
11504046500 3030 2e30 3030 3030 3030 000a
11504046513
Where the * denotes lines with only 0 digits. Then you can see why I called it wasteful | unknown | |
d7000 | train | Depending on your exact version of Apache, you may have encountered the same Apache rewrite bug that bit me: Internal URL rewrite no longer working after upgrading Apache to 2.4
See the workaround I linked to there. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.