text:
Q: Terminal emulator left-click to open link So I've been trying to get back to using Linux as my primary OS. I'm running Ubuntu 12.04 with Gnome 3. I've tried multiple terminal emulators, but they all seem to have a common failing: you need to hold the ctrl key down while left clicking to open links in a browser, or right click and select the context menu option "Open Link".
This is sub-optimal for me. The machine I'm using as a Linux desktop environment is the laptop I use for work. I use this when I'm working from home and I'm in my bedroom as opposed to my office; in my office I have my Windows gaming rig and my local Linux server (which I usually access over SSH from the laptop or the gaming rig, and run tmux inside). I often use this when my wife is sleeping and I don't have the space to use an external mouse. I know that's a lot of extra details (bordering on off-topic), but I'm trying to give a clearer picture of the reasoning behind my use case, and rule out certain solutions that won't work.
Right clicking and selecting open link and even holding the ctrl button down are easier when I can use the external mouse, but when I'm using the track pad, it's really uncomfortable to do so. Part of why I work from home and use the laptop in bed is because I have chronic pain conditions, so finding a way to customize my environment for my comfort is important to me, to help manage my disabilities.
I've tried gnome-terminal, terminator, guake, and several others that I can't remember at the moment. rxvt doesn't even seem to recognize links (in regular or unicode versions), same for xterm. Unicode also seems to be important so that tmux draws correctly (there might be config tweaks to work around that, but that's just what I noticed when testing now).
Any suggestions for how to configure one of the popular emulators to work with this, or another emulator to try? I've been using Guake lately since it seemed the best of them, but I'm definitely open to switching if it gets the job done. I would prefer not to hand-patch code, as I prefer to manage everything through apt if possible, but I will if it's necessary. I've avoided KDE-specific apps so far because of the extra overhead to get a single KDE app to run inside Gnome, but if there are no alternatives and it performs well enough, that's worth exploring as well.
I'm sorry if this seems like a trivial concern to folks, but this is actually the single-most annoying thing I'm dealing with trying to use Linux as a desktop environment (which in my opinion says a lot of good things about the state of the Linux desktop). However, with my disability, I'm getting tempted to set my default boot back to Windows as a result. I got very used to using putty-url which handles this perfectly.
Thanks for your help.

A: urxvt is probably the single most configurable emulator out there. Install it with
sudo apt-get install rxvt-unicode

Then edit the ~/.Xdefaults file adding the following:
URxvt.perl-ext-common: default,matcher
URxvt.urlLauncher: xdg-open
URxvt.matcher.button: 1
URxvt.matcher.pattern.1: \\bwww\\.[\\w-]\\.[\\w./?&@#-\[\]]*[\\w/-]

Using xdg-open allows you to use whatever browser you have specified in system settings (works for Gnome at least, unsure about KDE). Unfortunately, the default looks of urxvt are not, shall I say, very convincing, it's more like the old xterm than the modern gnome-terminal, and the configuration runs through config files rather than context menus. There is a tutorial on how to configure it, however.
Personally, I don't mind such configuration mode, in my experience you rarely want to reconfigure your terminal.


text:
Q: List the elements of the set I'm working on my math homework and I don't even know how to do this or what it is asking. Any help would be great!
Let $A = \{1, 2, 3\} \times \{1, 2, 3, 4\}$. List the elements of the set $B = \{(s, t) \in A \mid s \geq t \}$.

A: Here, $A$ is a Cartesian product between two sets, namely $\left\{1,2,3\right\}$ and $\left\{1,2,3,4\right\}$. This simply means that $A$ is the set of all possible ordered pairs formed by taking an element in each set.
$$A=\left\{(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4)\right\}$$
Next, the set $B$ is created by taking only those pairs $(s,t)$ of $A$ that satisfy the condition $s\ge t$.
Try to figure the answer by yourself, as this is, after all, homework... Then again, this is SE, so if you want to check, look below.

 $$B=\left\{(1,1),(2,1),(2,2),(3,1),(3,2),(3,3)\right\}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I fix this error related to Unique Non-Clustered index My table is called SalFactorHds, it has an unique index on column FactorNumFHS. While inserting values into the table I see this error:

cannot insert duplicate key row in object 'dbo.salfactorHds' with unique index UQ_FactorNumFHS

@FactorNumFHS is the parameter that stored procedure is sending.
The former code was this :
INSERT INTO SaLFactorHds (FactorNumFHS , column1 , columnb)
VALUES(@FactorNumFHS, 1, 2)

I changed it into this :
INSERT INTO SaLFactorHds (FactorNumFHS, column1 , columnb)
VALUES( (CASE
           WHEN NOT EXISTS (SELECT 1
                            FROM SALFactorHds
                            WHERE FactorNumFHS = @FactorNumFHS)
             THEN @FactorNumFHS
             ELSE ISNULL((SELECT MAX(FactorNumFHS)
                          FROM SALFactorHds
                          WHERE (CompanyNo = @CompanyNoFHS)
                            AND (FactorNumFHS <= (SELECT MaxNormalFactorSFT
                                                  FROM SALFactorTypes
                                                  WHERE CompanyNo = @CompanyNoFHS
                                                    AND (@FactorTypeFHS = SerialNoSFT)))
                            AND (FiscalYear = @YearFHS)) ,0) + 1
          END), 1, 2)

but I still see that error !!


text:
Q: Removing the unit "pm" from atomic positions The following input yields an output with the unit pm (0.01 Angstroms), how do you eliminate this unit so that only numbers are generated.
ChemicalData["OleicAcid", "AtomPositions"]

A: I think QuantityMagnitude is what you want:
QuantityMagnitude @ ChemicalData["OleicAcid", "AtomPositions"]


text:
Q: pyqt5: qt.qpa.xcb errors when launching app I'm migrating my application from pyqt4 to pyqt5.
Most of it works fine except for this issue I keep having on app launch:
$ python3 /tmp/loading.py
qt.qpa.xcb: failed to initialize XRandr
qt.qpa.xcb: X server does not support XInput 2

My application has a loading screen that I display while it loads some stuff:
import sys
import time

from PyQt5 import QtGui, QtCore, QtWidgets

from resources import Images

class LoadingScreen(QtWidgets.QMainWindow):
    def __init__(self):
        super(LoadingScreen, self).__init__()
        self.setWindowTitle('Loading MyApp...')
        self.setWindowIcon(QtGui.QIcon(Images.LOGO))
        self.setMaximumSize(600, 338)
        self.setMinimumSize(600, 338)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        self.palette = QtGui.QPalette()
        pixmap = QtGui.QPixmap(Images.LOADING_BACKGROUND)
        brush = QtGui.QBrush(pixmap.scaled(self.size(), QtCore.Qt.IgnoreAspectRatio))
        self.palette.setBrush(QtGui.QPalette.Background, brush)
        self.setPalette(self.palette)

        center = QtWidgets.QDesktopWidget().availableGeometry().center()
        self.move(center)

app = QtWidgets.QApplication(sys.argv)
loading_screen = LoadingScreen()
loading_screen.show()
time.sleep(5)
loading_screen.close()

In pyqt4 it works just fine, I see this simple loading window and then it closes.
On the hand, in pyqt5 I get the above errors in shell and the window never shows itself.
EDIT1
app = QtWidgets.QApplication(sys.argv)
loading_screen = LoadingScreen()
loading_screen.show()
foo()
loading_screen.close()
sys.exit(app.exec_())

EDIT2
import sys
import time

from PyQt4 import QtGui, QtCore

from drivertest.ui.gui.resources.resources import Images

class Form(QtGui.QDialog):
    """ Just a simple dialog with a couple of widgets
    """
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QtGui.QTextBrowser()
        self.setWindowTitle('Just a dialog')
        self.lineedit = QtGui.QLineEdit("Write something and press Enter")
        self.lineedit.selectAll()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()

    def foo(self):
        for _ in range(100000000):
            pass

class LoadingScreen(QtGui.QMainWindow):
    def __init__(self):
        super(LoadingScreen, self).__init__()
        self.setWindowTitle('Loading DriVerTest...')
        self.setWindowIcon(QtGui.QIcon(Images.LOGO))
        self.setMaximumSize(600, 338)
        self.setMinimumSize(600, 338)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        self.palette = QtGui.QPalette()
        pixmap = QtGui.QPixmap(Images.LOADING_BACKGROUND)
        brush = QtGui.QBrush(pixmap.scaled(self.size(), QtCore.Qt.IgnoreAspectRatio))
        self.palette.setBrush(QtGui.QPalette.Background, brush)
        self.setPalette(self.palette)

        center = QtGui.QDesktopWidget().availableGeometry().center()
        self.move(center)

app = QtGui.QApplication(sys.argv)
loading_screen = LoadingScreen()
loading_screen.show()

g = Form()
g.foo()

loading_screen.close()

g.show()

sys.exit(app.exec_())


text: Q: Legendary plans location (in RoS) I was wondering, as I'd really want to get my hands on the Plan for the "Cosmic Strand" legendray item, is there any particular location/bosses where one can found the plan for a particular legendary item? Or are all the plan dropped anywhere at random?


text:
Q: Don't found method so regen the file R.java I'm starting to program android Apps with eclipse. At the start all is Ok but after a week in all projects the file R.java was taked off and all projects not work. I search for mthods to regen it also here but any method that i try not work (clean, build automatically, Right click>preferences>java build path). Nothing work and i don't know how to solve (i also reinstall sdk and eclipse, only sdk....) The space in the local disc is sufficient to take all datas. How can i solve? Thanks you!
http://imageshack.com/a/img537/1047/Ngegx7.jpg

A: R files are automatically generated when project is built (like how you are doing clean - build). However, a common reason for R being not generated is when there is some error in your layout xml or etc. after cleaning (removing all generated stuff) the project.
Try to check the last place you edited and see if there is no error.


text:
Q: How to get focusable in a windowmanager view I use the WindowManager to create a view and add the view to the screen,but I cannot get the view focusable.I think I set the WindowManager.LayoutParams correct.
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);
    pushView = LayoutInflater.from(getApplicationContext()).inflate(
            R.layout.push, null);

    btn = (Button) findViewById(R.id.btn);
    cancelBtn = (Button) pushView.findViewById(R.id.cancelBtn);
    windowManager = getWindowManager();
    handler = new MyHandler();

    pushView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            System.out.println("onclick");
            windowManager.removeView(pushView);
        }
    });

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    PixelFormat.TRANSLUCENT);
            params.gravity = Gravity.TOP | Gravity.LEFT;
            params.y = 0;
            params.x = 0;

            windowManager.addView(pushView, params);

            new Timer().schedule(new TimerTask() {

                @Override
                public void run() {
                    Message msg = handler.obtainMessage();
                    handler.sendEmptyMessage(0x123);
                }
            }, 5000);

        }
    });

}

I want get the pushView'focusable to handle view's event.This problem has troubled me for a long time.Who can help me...

A: You simply need to remove the FLAG_NOT_FOCUSABLE flag:
params.flags = params.flags & ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

A: This is probably 4 years too late but have you tried using WindowManager.LayoutParams.TYPE_SYSTEM_ALERT instead of TYPE_SYSTEM_OVERLAY.
The former doesn't seem to have the focus deprivation limiation

A: I have figured out the question.Because I use the TYPE_SYSTEM_OVERLAY.
Window type: system overlay windows, which need to be displayed on top of everything else. These windows must not take input focus, or they will interfere with the keyguard. In multiuser systems shows only on the owning user's window.
So I cannot get the input focus.


text:
Q: Error when running spark kinesis streaming app in cluster mode (Amazon EMR) I am having some serious trouble trying to run a spark kinesis streaming app into an Amazon EMR cluster (1 master, 3 workers).
What I am trying to achieve is to build a FAT jar using the sbt assembly plugin in order to run a spark-submit command on the master node. The command I am using is the following:

spark-submit --class MyClass --master yarn --deploy-mode
  cluster --executor-memory 1g --executor-cores 2
  hdfs://url:port/my.jar

This application, receives incoming data from a kinesis stream and based on it, executes a request (post-back) to an url I can keep track on. I have tested my app locally by running it setting Master on SparkConfig to local[cores].
Moreover here is my code and my build sbt. My project is using scala 2.11.8 and sbt 0.13.8
build.sbt
name := "my-app"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
  "org.apache.spark" % "spark-streaming_2.11" % "2.0.0" % "provided",
  "org.apache.spark" % "spark-streaming-kinesis-asl-assembly_2.11" % "2.0.0",
  "org.scalaj" % "scalaj-http_2.11" % "2.3.0"
)

assemblyMergeStrategy in assembly := {
  case PathList("org", "apache", xs @ _*) => MergeStrategy.last
  case x =>
    val oldStrategy = (assemblyMergeStrategy in assembly).value
    oldStrategy(x)
}

MyClass
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.internal.StaticCredentialsProvider
import com.amazonaws.regions.RegionUtils
import com.amazonaws.services.kinesis.AmazonKinesisClient
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream
import com.keynetic_digital.model.RawKDLog
import org.apache.spark.SparkConf
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.kinesis.KinesisUtils
import org.apache.spark.streaming.{Duration, Milliseconds, StreamingContext}
import utils.HttpRequest

/**
  * Created by franco on 18/01/17.
  */
object MyClass {

  val awsAccessKeyId : String = "xxxxxxxxx"
  val awsSecretKey : String = "xxxxxxxx"
  val kinesisStreamName : String = "xxxxxxxx"
  val kinesisEndpoint : String = "https://kinesis.us-west-2.amazonaws.com"
  val appName : String = "xxxxxxxxx"

  def main(args: Array[String]): Unit = {
    //Set up Amazon Kinesis Client
    val kinesisClient : AmazonKinesisClient = createKinesisClient

    //Get all Kinesis shards
    val shards = kinesisClient.describeStream(kinesisStreamName).getStreamDescription.getShards.size()

    val batchInterval = Milliseconds(5000)

    // Create Spark Streaming Context
    val ssc : StreamingContext = createContext(batchInterval)
    val regionName = RegionUtils.getRegionByEndpoint(kinesisEndpoint).getName

    // Create the Kinesis DStreams
    val kinesisStreams = (0 until shards).map { i =>
      KinesisUtils.createStream(ssc, appName,
        kinesisStreamName,kinesisEndpoint,
        regionName,InitialPositionInStream.LATEST, batchInterval * 2,
        StorageLevel.MEMORY_AND_DISK_2)
    }

    //Unified all Streams
    val stream = ssc.union(kinesisStreams)

    //Get an RDD of Option(KDLog) items
    val jsons = stream.map(bytes => Option(RawKDLog.fromJson(bytes))).filter(_.isDefined)

    jsons.foreachRDD{rdd =>
      rdd.foreach{log =>
        handleLog(log)
      }
    }

    // Start the streaming context and await termination
    ssc.start()
    ssc.awaitTermination()
  }

  def createKinesisClient : AmazonKinesisClient = {
    //Set System Properties for Worker
    System.setProperty("aws.accessKeyId", awsAccessKeyId)
    System.setProperty("aws.secretKey", awsSecretKey)

    //Setting AWS Credentials
    val credentials : BasicAWSCredentials = new BasicAWSCredentials(awsAccessKeyId,awsSecretKey)

    //Setting AWS Credential Provider
    val provider : StaticCredentialsProvider = new StaticCredentialsProvider(credentials)

    //Setting Kinesis Client
    val kinesisClient : AmazonKinesisClient = new AmazonKinesisClient(provider)
    kinesisClient.setEndpoint(kinesisEndpoint)

    kinesisClient
  }

  def createContext(batchInterval : Duration) : StreamingContext = {

    // Create Spark Configuration
    val config = new SparkConf().setAppName(appName)

    // Create Spark Streaming Context
    new StreamingContext(config, batchInterval)
  }

  def handleLog(log : Option[RawKDLog]) : Unit = {
    if(log.isDefined){
      postBack(log.get)
    }
  }

  /**
    * Method that handles url postback requests
    */
  private def postBack(log : RawKDLog) = {
    //TODO url queryString replacement & request masking
    val postBackUrl : String = "url where I can track requests by tailing Nginx log"

    HttpRequest(postBackUrl) .asString

  }

}

After submiting the application in the cluster Master node, the following error happends.
17/01/18 14:39:26 INFO Client:
     client token: N/A
     diagnostics: User class threw exception: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 3.0 failed 4 times, most recent failure: Lost task 0.3 in stage 3.0 (TID 74, ip-172-31-42-151.us-west-2.compute.internal): java.lang.NoSuchMethodError: org.apache.spark.storage.BlockManager.get(Lorg/apache/spark/storage/BlockId;)Lscala/Option;
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.getBlockFromBlockManager$1(KinesisBackedBlockRDD.scala:104)
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.compute(KinesisBackedBlockRDD.scala:117)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
    at org.apache.spark.rdd.UnionRDD.compute(UnionRDD.scala:105)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
    at org.apache.spark.scheduler.Task.run(Task.scala:86)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
     ApplicationMaster host: 175.31.43.46
     ApplicationMaster RPC port: 0
     queue: default
     start time: 1484750075922
     final status: FAILED
     tracking URL: http://ip-175-31-46-219.us-west-2.compute.internal:20888/proxy/application_1484568737877_0012/
     user: hadoop
Exception in thread "main" org.apache.spark.SparkException: Application application_1484568737877_0012 finished with failed status
    at org.apache.spark.deploy.yarn.Client.run(Client.scala:1132)
    at org.apache.spark.deploy.yarn.Client$.main(Client.scala:1178)
    at org.apache.spark.deploy.yarn.Client.main(Client.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:736)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
17/01/18 14:39:26 INFO ShutdownHookManager: Shutdown hook called

I would really appreciate any guidance on this subject since I am quite new to developing and working with spark apps.

A: The solution to this problem was stated on this question Spark Streaming - Error when reading from Kinesis
Actually what happened was that I had set up my cluster with amazon emr 5.2.1 which uses Spark 2.0.2 and I bundled my FAT jar to use spark-streaming-kinesis-asl-assembly_2.11 2.0.0.
Therefore my application couldn't read input data from Kinesis
I switched to emr 5.0.0 which is the latest version using Spark 2.0.0 and everything executed as expected


text:
Q: Track test coverage history(trend) Goal - track unit/functional/integration tests coverage history on some regular basis (weekly, every release, etc) for relatively long period (6 months).
JUnit plugin in Jenkins out of the box does that per every build and problem here that it does not allow track specific slices (milestones, releases, etc) and history is kept for some fixed number of builds. So, here we are dependent on Jenkins workspace folder content which is not reliable.
Currently, we are capturing metrics from Jenkins and manually moving them into a table in confluence, so that we can use raw data to build graphs, trends. As you understand this approach requires a lot of manual effort and does not scale for cases when we need to track different test types, multiple projects
Is there any existing tool that provide capability to track history and show the trend?

A: Atlassian Clover can track historical coverage, however, keep in mind that you will still have to gather history point files in some place:

*

*https://confluence.atlassian.com/display/CLOVER/'Historical'+Report

*https://confluence.atlassian.com/display/CLOVER/clover-historypoint


text:
Q: How to change a shared gitlab runner token? I have one shared GitLab runner. To verify this I run the following command:
sudo gitlab-runner list

Which shows something like this:
Runtime platform                arch=amd64 os=linux pid=28276 revision=c127439c version=13.0.0
Listing configured runners      ConfigFile=/etc/gitlab-runner/config.toml
Shared shell runner - 1         Executor=shell Token=5_JqpessGzXasyqRyBP5 URL=https://gitlab.mysite.com/

I have a new GitLab instance and need to re-assign the runner to the new instance. This means a new token (the URL is the same).
Solution 1
I simply ran sudo gitlab-runner verify --delete and then registed a new runner. Clearly not ideal, though it works.
Solution 2
A second solution I thought about was to go in the /etc/gitlab-runner/config.toml and change the token, but this did not work for some reason. I believe it did not work, because when I ran sudo gitlab-runner verify it failed. I guess it's possible my issue was elsewhere...?
How can I achieve this?

A: You need to unregister the runner, they are "throw away instances". Then you need to take a look into the Runners section of Gitlab admin panel. There you will find a token to register a new shared runner.
While registering the runner, the runner will get his own token to authenticate against Gitlab. This token has nothing to do with the registration token in the Runners section in the admin panel.


text:
Q: SEO angular2 multiple routes to one component I created an application with angular2. For internalization and SEO purpose the routes of my application should change. My question is how can I map multiple routes to one component for example the routes:
www.test.at/GERMANNAME/Vienna
www.test.at/ENGLISHNAME/Vienna

sould map to one component. How can I achieve this with the angular2 router? What I got so far is the following piece of code:
export const testRoutes: Routes = [
  {
    path: 'ENGLISHNAME', <-- How can i add the GERMANNAME route to this path without copy/pasting the whole path
    component: TestComponent,
    children: [
      {
        path: ':city',
        component: TestListComponent
      }
    ]
  }
];


text:
Q: Contact Form 7 Redirect in Thank you page By post ID or URL for Tracking Goal I want to redirect my contact Form 7 redirect to Thank you page by Post ID or Post URL. That's why I can track my Conversion Goal for an individual post.
For Extample: I have Project details page and here only one contact from. So it can redirect just one Thank you page. but I need thank you page for every single project and that may be used ID or URL.
How can I do this?

A: Use this code to redirect contact form on thankyou page :
document.addEventListener( 'wpcf7mailsent', function( event ) {
   window.location = 'www.pageurl?id=33';
}, false );

You need to put this code where you have added contact form. just create a single thankyou page, to identify page/post you can pass  id in the url parameter www.pageurl?id=33


text:
Q: how to flush macports installation queue? I wanted to install git with macports - it failed. ok. So I went with dmg - succeeded.
However, now I cannot remove git from some install queue and if I want install anything it still fetches git install command (which is failing btw).
so.. "sudo port install htop" still invokes "sudo port install git-core"
how to fix it?

A: htop uses a git repo.  You have to install git-core first.  Try this first:

sudo port clean git-core


text:
Q: T-SQL pivot inventory aging by day range Writing a T-SQL statement to display items in inventory broken out by day range (pivot).
For example from this inventory table:

ItemName
DateCreated
PO_ID

A
2020-10-07
0

B
2020-10-07
1

A
2020-10-22
2

A
2020-10-22
2

A
2020-10-22
2

B
2020-10-29
3

Would like to generate the bellow results (typically a pivot table), showing the number of pieces per ItemName per day range. The date used to calculate the # of days since DateCreated would be the day the report was ran or passed in as a parameter - in the example shown here, the date used is from '2020-11-07':

ItemName
0-10 days
11-20 days
21-30 days
>30 days

A
0
3
0
1

B
1
0
0
1

Not sure what would be the best way to write the statement to generate the above results?

A: I would use conditional aggregation:
select itemName,
       sum(case when datediff(day, dateCreated, getdate()) <= 10 then 1 else 0 end) as days_0_10,
       sum(case when datediff(day, dateCreated, getdate()) > 10 and
                     datediff(day, dateCreated, getdate()) <= 20
                then 1 else 0 end) as days_11_20,
       sum(case when datediff(day, dateCreated, getdate()) > 20 and
                     datediff(day, dateCreated, getdate()) <= 30
                then 1 else 0 end) as days_21_30,
       sum(case when datediff(day, dateCreated, getdate()) > 30 then 1 else 0 end) as days_31
from t
group by itemName

A: I would use something similar to the following query SQL Server:
SELECT *
FROM
    (
      SELECT [ItemName],[PO_ID],
CASE
    WHEN DATEDIFF(day, DateCreated, getdate()) BETWEEN 0 AND 10 THEN '0-10 days'
    WHEN DATEDIFF(day, DateCreated, getdate()) BETWEEN 11 AND 20 THEN '11-20 days'
WHEN DATEDIFF(day, DateCreated, getdate()) BETWEEN 21 AND 30 THEN '21-30 days'
    ELSE '>30 days'
END AS PeriodCreated
      FROM [TableName])
    ) src
    pivot
    (
      COUNT(PO_ID)
      FOR PeriodCreated in ([0-10 days], [11-20 days], [>30 days])
    ) piv


text:
Q: Possibly processing same message in DB Queue (SQL Server) We experience sometimes that a message in our job queue is processed two times. In our system environment there is two services that can process messages from the queue table T_JOB_DIRECT.
Below you can see the stored procedure that is called by the service that is suppose to pick a message from the queue.
Can you see if there are some obvious mistake made that would make it possible for the two services to pick the same message from the T_JOB_DIRECT table?
CREATE       PROCEDURE [dbo].[usp_GetOneBatchJobForExec]
@sMachineName NVARCHAR(50)
AS

BEGIN
DECLARE @JOB_DIRECT_ID INTEGER

  SET NOCOUNT ON
  SET TRANSACTION ISOLATION LEVEL READ COMMITTED

  IF RTRIM(ISNULL(@sMachineName, '')) = '' BEGIN
    RAISERROR('@sMachineName parameter must be supplied!',16,1)
  END
  ELSE
  BEGIN
    SET @JOB_DIRECT_ID = 0
    WHILE @JOB_DIRECT_ID IS NOT NULL
    BEGIN
      -- If there is an job that has been marked for this service then return that.
      SET @JOB_DIRECT_ID = NULL
      SELECT TOP 1 @JOB_DIRECT_ID = JOB_DIRECT_ID FROM dbo.T_JOB_DIRECT WHERE IN_PROCESS_BY = @sMachineName
      IF @JOB_DIRECT_ID IS NULL
      BEGIN

        -- else take highest prioritized job that is free
        SELECT TOP 1 @JOB_DIRECT_ID = JOB_DIRECT_ID
        FROM dbo.T_JOB_TYPE AS JY
          INNER JOIN dbo.T_JOB_TYPE_ON_INST AS JTI
            ON JY.JOB_TYPE_ID = JTI.JOB_TYPE_ID
          INNER JOIN dbo.T_JOB_DIRECT AS JD
            ON JD.JOB_TYPE_ID = JTI.JOB_TYPE_ID
          AND JD.INST_ID = JTI.INST_ID
        WHERE JD.IN_PROCESS_BY IS NULL AND JD.START_DATETIME < GETDATE()
        ORDER BY JD.START_DATETIME DESC, JTI.PRIORITY DESC

        IF @JOB_DIRECT_ID IS NOT NULL
        BEGIN
          --Mark the job as taken and pick it up the next loop OR if update misses (someone else got it before) then get anotehr i next loop.
          UPDATE dbo.T_JOB_DIRECT SET IN_PROCESS_BY = @sMachineName WHERE JOB_DIRECT_ID = @JOB_DIRECT_ID AND IN_PROCESS_BY IS NULL
        END
      END
      ELSE
      BEGIN
        -- Return job information for the selected job.
        SELECT TOP 1 JD.*, JY.JOB_NAME
        FROM dbo.T_JOB_TYPE AS JY INNER JOIN dbo.T_JOB_TYPE_ON_INST AS JTI
            ON   JY.JOB_TYPE_ID = JTI.JOB_TYPE_ID
          INNER JOIN dbo.T_JOB_DIRECT AS JD
            ON   JD.JOB_TYPE_ID = JTI.JOB_TYPE_ID
          AND JD.INST_ID = JTI.INST_ID
        WHERE JOB_DIRECT_ID = @JOB_DIRECT_ID

        --Set ID NULL to exit the loop
        SET @JOB_DIRECT_ID = NULL
      END
    END  --LOOP

  END  --IF RAISE

END

EDIT
I got some feedback from the original creator of the procedure and he says that the reason that the procedure should be able to be executed without a transaction but still manage a race condition.
The race should be managed by the UPDATE.
UPDATE dbo.T_JOB_DIRECT SET IN_PROCESS_BY = @sMachineName
WHERE JOB_DIRECT_ID = @JOB_DIRECT_ID AND IN_PROCESS_BY IS NULL

it should only pick one job with the same ID and if IN_PROCESS_BY = NULL. That is only be able to pick the job if and only if noone else has picked it between the select and update.
The procedures should be able to handle a race and he don't think you have a valid point there.
Without "AND IN_PROCESS_BY IS NULL" we sure would have a problem though.

A: It looks like you have a race condition. Specifically, there is time between when you select the row and when you update it as "in process". You can get around this with some query hints and wrapping the select and update in a transaction. Your select can look something like:
IF @JOB_DIRECT_ID IS NULL
BEGIN
    BEGIN TRANSACTION;

    SELECT TOP 1 @JOB_DIRECT_ID = JOB_DIRECT_ID
    FROM dbo.T_JOB_TYPE AS JY
    INNER JOIN dbo.T_JOB_TYPE_ON_INST AS JTI
       ON JY.JOB_TYPE_ID = JTI.JOB_TYPE_ID
    INNER JOIN dbo.T_JOB_DIRECT AS JD with (updlock, rowlock, readpast)
       ON JD.JOB_TYPE_ID = JTI.JOB_TYPE_ID
       AND JD.INST_ID = JTI.INST_ID
    WHERE JD.IN_PROCESS_BY IS NULL
       AND JD.START_DATETIME < GETDATE()
    ORDER BY JD.START_DATETIME DESC, JTI.PRIORITY DESC;

    IF @JOB_DIRECT_ID IS NOT NULL
    BEGIN
        -- Mark the job as taken and pick it up the next loop
        -- OR if update misses (someone else got it before)
        -- then get another in next loop.
        UPDATE dbo.T_JOB_DIRECT
        SET IN_PROCESS_BY = @sMachineName
        WHERE JOB_DIRECT_ID = @JOB_DIRECT_ID
           AND IN_PROCESS_BY IS NULL
    END
    COMMIT TRANSACTION;
END

As an aside, I'd add a unique filtered index on the t_job_direct table on the in_process_by column where the value is not null if you don't already have one. That will prevent more than one row being in process by a given machine at any time.

A: Thanks to the comment of Ben Thul above I changed the stored procedure to take advantage of the OUTPUT clause. The original sp was written before the OUTPUT clause was introduced in SQL Server.
Here is the final new version.
CREATE       PROCEDURE [dbo].[usp_GetOneBatchJobForExec]
@sMachineName NVARCHAR(50)
AS
BEGIN

SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

with cte as (
    SELECT TOP(1) JD.*, JY.JOB_NAME
    FROM dbo.T_JOB_TYPE AS JY
        INNER JOIN dbo.T_JOB_TYPE_ON_INST AS JTI
            ON JY.JOB_TYPE_ID = JTI.JOB_TYPE_ID
        INNER JOIN dbo.T_JOB_DIRECT AS JD WITH (ROWLOCK, READPAST)
            ON JD.JOB_TYPE_ID = JTI.JOB_TYPE_ID
        AND JD.INST_ID = JTI.INST_ID
    WHERE (JD.IN_PROCESS_BY IS NULL OR JD.IN_PROCESS_BY = @sMachineName) AND JD.START_DATETIME < GETDATE()
    ORDER BY JD.IN_PROCESS_BY DESC, JD.START_DATETIME DESC, JTI.PRIORITY DESC
)
UPDATE cte
SET IN_PROCESS_BY = @sMachineName
OUTPUT inserted.JOB_DIRECT_ID, inserted.JOB_TYPE_ID, inserted.INST_ID, inserted.JOB_QUEUE_ID, inserted.JOB_DATA, inserted.REG_DATETIME,
        inserted.REG_USER_ID, inserted.JOB_TIME_ID, inserted.IN_PROCESS_BY, inserted.START_DATETIME, deleted.JOB_NAME

END


text:
Q: Symfony - Doctrine how distinct SUM from JOIN? I'm working on Symfony 3.4 and I have some troubles on a query, I will try to explain clearly !
I have 3 entities Website, Mission, Gain with :
Website OneToMany Mission
Mission OneToMany Gain

I have a price field in Gain entity
I need to SUM the price value for each Gain for each Website, but in my case it doesn't work.
In my example I have :

*

*1 Website

*3 Mission (linked to the Website)

*1 Gain for each Mission (linked to Mission) with values in price : 100, 200, 300

This is my query (w is Website, m is Mission, g is Gain):
$builder = $this->createQueryBuilder('w');
$builder->innerJoin('w.missions', 'm');
$builder->innerJoin('m.gains', 'g', 'WITH','g.user = w.user');
$builder->select('w', 'SUM(g.price) as gain');
$builder->addSelect('COUNT(distinct m) as nbMissions');

$results = $builder->getQuery()->getResult();

With this query, I have in the SUM result gain the value 1800 instead of 600.
In fact it is the good result but multiplied by the number of missions (600*3). In nbMissions I have 3.
Do you know how can I have the right result ?
Thanks !


text:
Q: Flutter- Expansion Panel for TextField Expansion Panels in flutter are great. They require header and body along with isExpanded property to be declared to be able to construct an Expansion panel. Like this:
return new ExpansionPanel(
  headerBuilder: (BuildContext context, bool isExpanded){
                   return Text('header');},
  isExpanded: false,
  body: new Text(body[enter image description here][1]),
);

I want to build an Expandable TextField. I can wrap the text field with Expansion panel, and specify the TextField as Body. But there is a big white space that between header and body. Also, I would like to just expand the body and remove the header altogether, so that I can see the first Text line of body without expanding, and the rest of the body opens up when I expand the Expansion panel. Does anyone know of any work arounds for this? Or any different widget or material component I can use.
Here is a screenshot of how it looks right now, see there is a lot of spacing in between header and body.

If this questions interests you, upvote it, to draw out better answers. Flutter has a lot to come, and we need a stronger stack overflow community.

A: I'm not sure the ExpansionPanel is what you want.
If I understood correctly, you want a Text with two states. In the first state the Text has only one line, in the second state the Text can display all its lines. When the user taps on this widget, it switches from one state to the other.
I created a simple widget for that:
class ExpandableText extends StatefulWidget {
  const ExpandableText(
    this.data, {
    Key key,
  }) : super(key: key);

  /// The text to display.
  ///
  /// This will be null if a [textSpan] is provided instead.
  final String data;

  @override
  _ExpandableTextState createState() => new _ExpandableTextState();
}

class _ExpandableTextState extends State<ExpandableText> {
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleOnTap,
      child: new Text(
        widget.data,
        maxLines: _isExpanded ? null : 1,
      ),
    );
  }

  void _handleOnTap() {
    setState(() {
      _isExpanded = !_isExpanded;
    });
  }
}

There is no animations in here so it's rather abrupt. Feel free to customize the above widget to fit your needs.


text:
Q: MySQL Left Join to Union I'm trying to do a left outer join to a union. The query runs, but does not display the columns from the union.  What am I missing?  This is my query:
SELECT p.profile_record_id,
       p.first_name,
       p.last_name,
       l.entry_id,
       l.when_logged,
       l.amount,
       l.reason_text
FROM   member_profile p
       LEFT OUTER JOIN authorize_net_log l
                    ON ( p.profile_record_id = l.profile_record_id )
       LEFT OUTER JOIN (SELECT assigned_entry_number,
                               payment_status AS e_status,
                               'vehicle'      AS type,
                               profile_record_id
                        FROM   event_entry
                        UNION
                        SELECT '',
                               co_payment_status,
                               'driver',
                               profile_record_id
                        FROM   event_co_driver) u
                    ON ( p.profile_record_id = u.profile_record_id )
WHERE  l.response_code = '1'
       AND l.reason_code = '1'

A: You probably should add them to the SELECT list:
SELECT  u.*, p.profile_record_id, p.first_name, p.last_name, l.entry_id, l.when_logged, l.amount, l.reason_text
FROM    ...


text:
Q: (Unreal Engine) iOS Deployment Without Paid Developer Account Won't Work For days now I am trying to find out what I'm doing wrong can't find the right solution.
I am new to the Unreal Engine and currently trying to figure out how all of it works. I downloaded the Epic Zen Garden and the Sun Temple example project off of the "Engine Feature Samples" and wanted to deploy them on my iPhone XR, but I can't.
I looked through about 10 possible solutions but none of them really worked and somehow there are several ways to handle this matter so I wanted to ask you to eventually share your workflow regarding building apps on iOS using Unreal.
My setup:
Unreal 4.23 and 4.24 /
iMac 2017 with OS Catalina 10.15.1 /
iPhone XR with iOS 13.3 /
Xcode 11.3
As the title mentions, I am trying to find a solution without having to spend $99 for the Paid Developer Program.
What I did so far:
I've opened up Xcode and created a new project. I automatically signed in with my free developer account, used an bundle identifier and deployed the app on my iPhone. What happened now is that a provisioning profile and a certificate is created.
I then switched back to Unreal, opened the project settings -> iOS and used the same bundle identifier like the on in the Xcode project.
The mobile provision and certificate show "valid" and I also checkmarked them.
I then choose my device within Unreal under "Launch" and 2 error messages pop up saying "Provision not found" "Signing key not found". Why though? It shows up as "valid".
When I try to launch Launch -> Project Launcher -> iPhone -> I suddenly receive following error:
ERROR: Stage Failed. Missing receipt '/Users/myName/Documents/Unreal Projects/SunTemple/Binaries/IOS/SunTemple.target'. Check that this target has been built.
So what am I doing wrong? This solution came up the most while searching for ways to handle this problem.
I would be thankful if anyone could share his steps.
Best regards
Daniel


text:
Q: Codeigniter delete function not working I am trying to build a simple delete function in my project to delete data from a table. I .can't figure out why it is not working. I used the codeigniter user guide to help me out with this. I am getting an error and don't know why. Here is my controller, model and view for the delete:

A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$id

Model
function delete()
{
    $this->load->database();
    $tables = array('info', 'info2');
    $this->db->where('id', 1);
    $this->db->delete($tables);

}

controller
 function del($tables){

if((int)$tables > 0){
          $this->info_model->delete($tables);
}

$data = $this->info_model->delete();
$data['query'] = $this->result_model->delete();

$this->load->view('info_view',$data);
 }

view
//this line gives me the error

 <td><?php echo anchor('info_controller/del' . $row->id,'Delete')?> </td>

EDIT
I used this tutorial to make this
http://www.phpeveryday.com/articles/CodeIgniter-Form-Centralizing-$data-P291.html

A: In your controller Load your model like this
$this->load->model('deletion_model');

Then call the method of the deletion_model
$this->deletion_model->delete($id);

Make sure you load the model.
after that i suggest you pass value of id as string.
$this->db->where('id', '1');

OR
use the variable supplied to this function if you are not using static values
$this->db->where('id', $id);

Please read the guide properly
http://ellislab.com/codeigniter/user-guide/database/active_record.html#delete
You can also retrieve the id of the record for deletion by using
$id=$this->uri->segment(3); // depending on which segment the id is

A: *

*I do not see any $row object in your controller, although you use it in your view: $row->id

*Your model is not returning anything.

*If you delete a specified row, $object->id will cease to exist.

*The link in your view it states that you want to show a delete link, but you use that view in the controller that deals with the actual delete action.

Edit:
Because you try to iterate in your view through query results, $data['query'] from your controller should point to a select statement.


text:
Q: What causes the additional raw in foreach loop? I have a for each loop which is used to print the serial numbers of a given sale item of an order, which was done based on this question
    if (($c["current_state"] == '16') || ($c["current_state"] == '4')) {
        $snlst = $mysqli->query("SELECT sn FROM ps_serials WHERE id_product={$aritmlst["product_id"]} AND id_order=$oid ORDER BY sn ASC");

        while ($id = mysqli_fetch_array($snlst)) {
            $ids[] = $id;
            foreach ($ids as $key => $id) {
                echo "
Serial Number ".($key +1)."	".$id['sn']."
";
            }
        }
    }

But the problem is that I get an additional table raw for my listing. Why is that?

A: I don't see the need for two loops. IMHO this should be enough code:
if (($c["current_state"] == '16') || ($c["current_state"] == '4')) {
    $snlst = $mysqli->query("SELECT sn FROM ps_serials WHERE id_product={$aritmlst["product_id"]} AND id_order=$oid ORDER BY sn ASC");
    $i = 0;
    while ($row = mysqli_fetch_array($snlst)) {
        $i++;
        echo '
Serial Number ' . $i . '	' . $row['sn'] . '
' . PHP_EOL;
    }
}

A: rewrite this line:
while ($id = mysqli_fetch_array($snlst)) {
            $ids[] = $id;
            foreach ($ids as $key => $id) {
                echo "
Serial Number ".($key +1)."	".$id['sn']."
";
            }
        }

to this:
while ($id = mysqli_fetch_array($snlst)) {
    $ids[] = $id;
}
foreach ($ids as $key => $id) {
 echo "
Serial Number ".($key +1)."	".$id['sn']."
";
            }

A: then try a simple for loop, instead of a foreach loop:
for($i= 0; $i < count($ids); $i++)
{
  echo "
Serial Number ".($i+1)."	".$ids[$i]['sn']."
";
}


text:
Q: MPL Map Instantiate Type I have the following:
class Message
{
public:
    bool process()
    {
        return doProcess();
    }
protected:
    virtual bool doProcess() = 0;
};

class Hello : public Message
{
protected:
    bool doProcess()
    {
        return false;
    }
};
typedef typename boost::mpl::map< boost::mpl::pair< boost::mpl::int_< 0 >, Hello > > map;

struct Generator
{
    typedef void result_type;
    template< typename t_type >
    void operator()(std::vector< boost::shared_ptr< Message > >& processors,
                    t_type p_element)
    {
        typedef typename boost::mpl::at< map, t_type >::type c_instanceType
        boost::shared_ptr< Message > temp(reinterpret_cast< Message* >(new c_instanceType));
        p_processors[p_element] = temp;
    }
};

This is then invoke like so:
class MessageProcessor
{
public:
    MessageProcessor() :
        m_processors(12)
    {
        // eventually there will be 12 different messages so I will add
        // them to the mpl map and adjust the range
        boost::mpl::for_each< boost::mpl::range_c< boost::uint8_t, 0, 1 > >
        (
            boost::bind(Generator(), boost::ref(m_processors), _1)
    }
private:
    std::vector< boost::shared_ptr< Message > > m_processors;
};

This code compiles cleanly; however, when the function is later invoked like so:
m_processors[0]->process();

A segmenation fault occurs on the line in the process function that returns do process. I am working in gcc 4.8 with boost version 1.55. Also note this isn't the entire code. When walking through with the debugger I see that the vptr appears to be null when invoking the doProcess, so the child class doesn't seem to exist. Any ideas on how to fix this?

A: So the issue appears to be that the type is not actually found when doing at<> and something else is being returned instead of the Hello type. It looks like the type that is passed in by boost::for_each is of type, boost::mpl::integral_c<boost::uint8_t, 0> which doesn't exist in the mpl map since I am storing boost::mpl::int_<0> as the key. Changing the key type in the map to boost::mpl::integeral_c< boost::uint8_t, 0 > does not segfault and performs as expected.


text:
Q: Насколько корректен такой подход к вёрстке? Bootstrap4 Верстаю на bootstrap, но меня терзают сомнения насчёт правильности моего подхода. Прошу подсказать, насколько объективна такая вложенность элементов и каким образом можно выравнять элементы по вертикали, не задавая принудительно высоту блоку с классом row?
Пример кода:

Задачи:

*

*У каждой секции свой background-color.

*Секции должны быть отцентрированы по центру.

*Контент (текст, изображения) должны быть отцентрированы по вертикали.

Вопросы:

*

*Насколько корректно решать задачу №1 следующей структурой?

.container-fluid > .container ?

Может есть более простое решение?

*Насколько корректна следующая вложенность элементов? Мне не нравится, что до контента аж 3 "обёртки", или это в порядке вещей?

.container-fluid > .container > .row

*Чтобы отцентрировать по вертикали я добавляю к обёртке контента

.row

класс
align-items-center

НО, для этого необходимо блоку с .row принудительно указывать высоту (добавляю класс .tm-height)
Насколько это правильный подход? Может, есть свойство, которое автоматически придаёт .row высоту родительского элемента?

A: Для центровки лучше подойдет flexbox


text:
Q: Deleting worksheets by macro I'm trying to delete all sheets except the first sheet, but I get an

error 9 "subscript out of range" appears.

How can I fix it?   Thanks in advance.
Dim Udalenie As Integer
   If ThisWorkbook.Worksheets.Count > 1 Then
      For Udalenie = 2 To ThisWorkbook.Worksheets.Count
         ThisWorkbook.Sheets(Udalenie).Delete
   Next Udalenie
End If

A: Because each time you delete one sheet, the Excel will remove it from this sheet from Worksheets and the total sheets count will minus 1.
Dim Udalenie As Integer
If ThisWorkbook.Worksheets.Count > 1 Then
For Udalenie = 2 To ThisWorkbook.Worksheets.Count
ThisWorkbook.Sheets(2).Delete
Next Udalenie
End If


text:
Q: C function syntax On this page : http://www.scs.stanford.edu/histar/src/pkg/uclibc/libc/sysdeps/linux/x86_64/sigaction.c
I see these two lines :
extern void restore_rt (void) asm ("__restore_rt") attribute_hidden;
extern void restore (void) asm ("__restore") attribute_hidden;

What is this syntax? Is it setting up restore_rt to be a function that has inline asm("__restore_rt") as its body?
Thanks!

A: Using asm in a function declaration is a GCC extension (also supported by Clang/LLVM) called asm-label. It is setting the assembler and linker known name of the function.
BTW, in your code attribute_hidden is probably a macro for some function attribute, probably __attribute__ ((visibility ("hidden")))

A: Apparently it's a way to replace the symbolic name of a C function...

In order to change the name of a function, you need a prototype declaration, because the compiler will not accept the asm keyword in the function definition:

extern long Calc(void) asm ("CALCULATE");

Calling the function Calc() will create assembler instructions to call the function CALCULATE.

Search for "Replacing symbolic names of C functions" in this document


text:
Q: Multiple Condition I have "object doesn't support this method" error when trying to do a comparison of column cross sheets. . If both column A and B in sheet 1 matches both column A and B in sheet 2, it will display the match in sheet 3.

A: There were a number of issues in your code. In the future, please post the actual code (not screenshot).

*

*Watch out for "And" vs "&" in your if statement.

*".value" not ".values" in your vars.

*"Dim as string" since we're working with the cell.

*"Worksheet." not "Worksheets."

*I don't think you need a "Set" for these. (could be wrong)

Try the code below, it works for me. You may need to modify the lines writing to the "match" sheet.
Sub find()

Dim a As String
Dim b As String
Dim c As String
Dim d As String

a = Worksheets("sheet1").Range("a1").Value
b = Worksheets("sheet2").Range("a1").Value
c = Worksheets("sheet1").Range("b1").Value
d = Worksheets("sheet2").Range("b1").Value

If a = b And c = d Then

Worksheets("match").Range("A65536").End(xlUp).Offset(1, 0).Value = c
Worksheets("match").Range("A65536").End(xlUp).Offset(0, 1).Value = c

End If
End Sub


text:
Q: Posting in behalf of Wordpress "Contributor" user I have a news website belongs to old school, and I am receiving articles/opinions through email, and I manage adding theme my self.
I am planning now to switch to Wordpress and until I can enable all writers to post their articles by giving them "Contributor" role, is there any Wordpress plugin that enable Admin/Author to post an article in behalf of any "Contributor" user?
Thanks

A: Your editors don't need a plugin for this.  On the admin page in which you edit posts (or pages) near the bottom there's a dropdown list from which your editor can select the post's author. The selected author shows up as the post's author on the front end.
Your contributors will be able to write and edit their own posts. But, only an editor or administrator can publish them: make them visible on the front end.
That's handy: it lets you have contributors you don't trust completely. Editors vet their work before it shows up on the site.
But, if your editors aren't diligent, your contributors will never see their work published. On a volunteer site (such as your application) they'll become discouraged and stop writing stuff.
You may want to err on the side of letting people publish stuff, then removing it if you don't like it, or if it's spam, or whatever. To do that you make people "editors" rather than contributors.

A: Yes , learn here about the editor role , you can create as many as editors from wp-admin panel and editors can create and modify the posts via their provided login or their created login.
Editor capabilities : https://codex.wordpress.org/Roles_and_Capabilities#Editor
You can also manage their capabilities by using : User Role Editor plugin

A: I don't know of any such plugins but if the number of articles posted by contributors are less than you can simply write that article and publish it. Once publish you can than change the author to any contributor from the list on the posts page.


text:
Q: Windows support software could not be saved to the selected drive I been installing Windows on my new MacBook Pro 13" 2017 Touchbar (MacOS Sierra) but I have been stuck because I get the error Windows support software could not be saved to the selected drive ... I tried installing it using a 16gb USB stick  (MSDOS fat32) and no USB since my MacBook can install Windows even without USB flash drive (as mentioned by apple in their website.) Can someone help me with these problems?

A: Cause
Apple allows Windows Installation, by first copying the entire ISO into a temporary storage area.  Most of the time it works, because there is enough space available.
When we use a larger ISO, like the 32-bit + 64-bit Windows ISO, it requires about 6.5 GB just for the storage, let alone uncompressed files usage.  Apple tried to download Windows support software onto that partition.  This is where the issue happens.  The package requires at least 1 GB, and it would not get it because of the ISO.
Solution

*

*Use the 64-bit ISO (3.5GB) instead of the 32-bit + 64-bit Windows ISO for a x64 MacBook (all current generation ones)

*Use the 32-bit ISO (3.5GB) instead of the 32-bit + 64-bit Windows ISO for a x86 MacBook (2011 etc.)


text:
Q: Data-Driven Unit Test with MSTest : How to read and validate records from CSV file? I use the MsTest and Data Driven approach for unit testing.
So far I have a Data.csv file with 5 rows added in my Unit Test project and I want to validate and output the UserId for each corresponding orgId and username.
For example, for Orgid '80010' and username 'Malika' - expected userid = 0000000047
data.csv file
How can I set up the data driven test method to read and validate the correct userId from the .CSV file?
C# Code:
using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AuthenticationServiceTest
{
    [TestClass]
    public class UT_GetUserIdFromUserName
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", @"Data\Data.csv", "Data#csv",
        DataAccessMethod.Sequential)]
        public void TestMethod1()
        {
            // Arrange
            int ExpUserId = Convert.ToInt32(TestContext.DataRow["0000000047"]);
            int orgId = Convert.ToInt32(TestContext.DataRow[1]);
            int username = Convert.ToInt32(TestContext.DataRow[2]);

            // Act
            string UserId = string.Empty;

            // Assert
            Assert.AreEqual(ExpUserId, UserId);
            Console.WriteLine("Expected UserId: " + ExpUserId);
            Console.WriteLine("Actual UserId: " + UserId);

        }

    }
    }

A: You don't have to pick a specific ID the unit test engine will take care of parsing the file row by row.
You have to use the the TestContext.DataRow["column" or index] to get the value from a specific column of the CSV file.
int ExpUserId = Convert.ToInt32(TestContext.DataRow["0000000047"]);

Should be either
int ExpUserId = Convert.ToInt32(TestContext.DataRow[0]);

or
int ExpUserId = Convert.ToInt32(TestContext.DataRow["userId"]);


text:
Q: QFileDialog view folders and files but select folders only? I'm creating my own custom file dialog using the following code:
file_dialog = QtGui.QFileDialog()
file_dialog.setFileMode(QtGui.QFileDialog.Directory)
file_dialog.setViewMode(QtGui.QFileDialog.Detail)
file_dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)

The behaviour that i'm interested in is for the user to be able to view both files and folders, but select folders only. (making files unselectable). Is that possible?
Note:
Using the DirectoryOnly option is not good for me since it doesn't allow you to view files, just folders.
Edit (extra code that i forgot to add which responsible for being able to select multiple folders instead of just one):
file_view = file_dialog.findChild(QtGui.QListView, 'listView')
if file_view:
    file_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
f_tree_view = file_dialog.findChild(QtGui.QTreeView)
if f_tree_view:
    f_tree_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

A: To prevent files being selected, you can install a proxy model which manipulates the flags for items in the file-view:
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.Directory)
dialog.setOption(QFileDialog.DontUseNativeDialog, True)

class ProxyModel(QIdentityProxyModel):
    def flags(self, index):
        flags = super(ProxyModel, self).flags(index)
        if not self.sourceModel().isDir(index):
            flags &= ~Qt.ItemIsSelectable
            # or disable all files
            # flags &= ~Qt.ItemIsEnabled
        return flags

proxy = ProxyModel(dialog)
dialog.setProxyModel(proxy)

dialog.exec()


text:
Q: Set a proxy individually for each WebBrowser? I just found out how to change proxies without restarting the WebBrowser control, but that seems to set it for ALL WebBrowser controls on my form. I want to be able to set a different proxy for each control. Is this possible?
If not, is there any tricks I can do to get around this? Maybe some kind of daemon that watches a port and translates that request into a proxy request? For example:
Request on port 12345 -> Connect to url on port 80, but use proxy 1.2.3.4:8080
Request on port 12346 -> Connect to url on port 80, but use proxy 6.4.5.1:8080

A: In our application we resolved this launching every browser in a separate process and reparenting it.
We don't reach to set a proxy for all webbrowser in the same process.


text:
Q: clone git repository on my gradle using Grgit I have a gradle project which runs a script, and somewhere in it, I need to clone a git repository.
I had it running before with svn, but I change our company SCM to gitlab, and I need to change the code so it'll now clone the repo from git.
I need something that will work similar to this SVN code:
task exportLibs(type: SvnExport) {
  svnUrl = "http://<svn-url>"
  targetDir = "<target-dir-to-download-files>"
}

So I read about Grgit, but there was not a single example online, how to do a simple git clone (only this link http://ajoberstar.org/grgit/docs/groovydoc/org/ajoberstar/grgit/operation/CloneOp.html). If there is someone who can help me walkthrough this problem or maybe produced me to his grgit project so i will learn from it, it'll be awesome!
--Edit--
when i tried to use the grgit as below:
group 'test'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        maven {
             url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "org.ajoberstar:gradle-git:1.7.2"
    }
}

apply plugin: 'java'
apply plugin: 'org.ajoberstar.grgit'

org.ajoberstar.grgit.auth.hardcoded.allow=true
task pullFromGit{
    doLast {
        //grgit.pull()
    }
}

sourceCompatibility = 1.8

repositories {
     mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

i've use this properties to initial it, and i got the following error:

A problem occurred evaluating root project 'grgit'.
Could not get unknown property 'org' for root project 'grgit' of type org.gradle.api.Project.

A: There is a link on the github page of the project to some examples and the API documentation. The following snippet would solve your problem (in this case, it will clone the grgit project to the grgit directory)
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.ajoberstar:grgit:1.7.2'
    }
}

task hello {
    doLast {
        org.ajoberstar.grgit.Grgit.clone(dir: 'grgit', uri: 'https://github.com/ajoberstar/grgit.git')
    }
}

Answer to the edited question
The documentation states that org.ajoberstar.grgit.auth.hardcoded.allow is a system property. Your assignment is not a valid way to set system properties, see the answer to this question for examples on setting system properties in groovy.

A: my code probably had some special imports in it, cause a the end the only clone that i could have done is shell exec.
the problem is solved, but not the bug i had...


text:
Q: How to avoid margin when combining ListDensityPlot and an Image? I have an image img1 and some data with a density plot plot1 to reflect the target position of the image. I tried to combine img1 and plot1 as below:-
targetPosition = BlockRandom[SeedRandom[123]; RandomReal[100, {35, 50}]];
img1 = ImageCrop[ExampleData[{"TestImage", "Airport"}], {1000, 700}];
plot1 = ListDensityPlot[Exp@targetPosition,
  AspectRatio -> ImageAspectRatio@img1, PlotRange -> All,
  ImageSize -> ImageDimensions[img1], Axes -> False, Frame -> None];
ImageAdd[ImageMultiply[plot1, 0.6], ImageMultiply[img1, 0.4]]

As you can see, there's still a margin here. Thus the position will have errors due to the margin. How can I get rid of the margin?
Many thanks!

A: PlotRangePadding >> Details

PlotRangePadding -> Automatic adds a total of 4% for PlotRange settings All, Full, and Automatic. For explicit settings, it adds no padding.

Adding PlotRangePadding -> 0 to ListDensityPlot gives


text:
Q: Which Python module ,libraries are available for OSX Automation? I am searching for any module for OSX automation like opening any app via Python and controlling mouse, keyboard via Python etc. I tried with AppleScript but I was wondering if I can access mouse, keyboard and can automate any app on OSX using Python? I found pyauto, If there is any other good Python library, module for OSX automation please let me know.

A: I too am looking for a good python module to use 'applescript' within python. In fact this is how I got here. I was unable to find anything so I had to come up with my own solution.
What works well for me is to call osascript from within my python programme using the subprocess module.
More precisely, (see the code below for an example), if I want to add something to my calendar I generate the applescript that does it as string in my python programme and then pipe it into osascript.
This is not super elegant and probably also not super fast but it works well. So, I am currently writing a calendar module that has python functions for adding events, getting list of events .... and each generates the applescript as string and calls osascript.
It sounds terrible but works quite well and once you have a module for your favourite programme you don't need to worry anymore about applescript.
One needs a way to encode in the applescript the return data and then decode it in the python programme. As for me most data passed to and from the applescript are dictionary-like, this has not been an issue so far using the re module.
Here is an example to get the uid of the calendar "Birthdays".
The main problem with my method is that I need to write wrapper functions for everything I want to access in applescript. A tiresome process.
The main advantage I see is a) it works and I get where I want and b) it seems future proof. For, if apple at some point discards applescript in favour of javascript or whatever, then all my programmes will still work once I adapted the wrapper modules.
Anyway ...
Hope that helps.
By the way, if anyone knows of a better way let me know. Or if someone does not know of a better way but likes my approach and would be interested in helping writing wrapper modules, let me know as well.
Here is the example.
Best,
Stephan
import subprocess

def asrun(ascript):
  "Run the AppleScript ascript and return the standard output and error."
  return subprocess.run(['osascript'],
                         input=ascript,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         encoding="utf-8")

def get_uid_of_calendar(name):
    script = '''\
    tell application "Calendar"
         return uid of calendar "'''+name+'''"
    end tell
    '''
    cal_res = asrun(script)
    return cal_res.stdout

get_uid_of_calendar("Birthdays")


text:
Q: How can I load my homemade 32bit cpp DLL into my canopy 3.5 32bit python? I am trying to load my DLL (32bit) file containing CPP functions into python. It works on python 3.7 (32bit) but it gives an error when using canopy 3.5 (32bit).
the code I use to load my dll:
import os
import ctypes

os.chdir(r"G:\DLLdirectory")
mydll = ctypes.cdll.LoadLibrary('MyDLL.dll')

If I run it on pyton 3.7 it works, if I run it with canopy 3.5 I get:
Traceback (most recent call last):
    File "DIR/PythonFile.py", line 26, in <module>
        mydll = ctypes.cdll.LoadLibrary('MyDLL.dll')
    File "DIR\Canopy32\edm\envs\User\lib\ctypes\__init__.py", line 425, in LoadLibrary
        return self._dlltype(name)
    File "DIR\Canopy32\edm\envs\User\lib\ctypes\__init__.py", line 347, in __init__
        self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found

If you change os.chdir() to sys.path.append() in canopy still the module is not found and in python 3.7 I get this error:
Traceback (most recent call last):
    File "DIR/PythonFile.py", line 26, in <module>
        mydll = ctypes.cdll.LoadLibrary('MyDLL.dll')
    File "DIR\Python\Python37-32\lib\ctypes\__init__.py", line 434, in LoadLibrary
        return self._dlltype(name)
    File "DIR\Python37-32\lib\ctypes\__init__.py", line 356, in __init__
        self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application

A: Welcome to StackOverflow!
Not sure whether this is the cause of the error msg that you saw, but FYI the C++ compiler used in building your extension should be the same one used to build the Python that you are using. As you can tell by typing python, Enthought's Python 3.5.2 is built with
Visual C++ 2015 (14.0) 1900
See https://stackoverflow.com/a/2676904/1988991
It's likely that you built your DLL with a later compiler. Since it seems to work with Python 3.7, Visual Studio 2017 or 2019 seem likely. See https://www.scivision.dev/python-windows-visual-c-14-required/

A: It turned out that the DLL was dependent on another DLL and this DLL was found in python automatically. However, in Canopy the second DLL needed to be loaded separately.


text:
Q: How to get additional Django Inline Formsets to POST to database I'm currently building out a Django ModelForm with an adjoining inline_formset. I'm also using a button with javascript to allow the user to add in more instances of the formset in the front-end. However, the issue im running into is that the extra instances of the formset that are added by the user, don't get sent to the database when the form is submitted.
I'm unsure as to whether it is an issue with the javascript itself. Or something more fundamental to do with the Django inline formsets. Any help would be much appreciated. Everything else is working fine; heres my HTML template for reference
{% extends 'main.html' %}
{% load static %}
{% block content %}

    <form class="form" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {% for field in form %}

{{field.label}}:

{{field}}

        {% endfor %}

            {{formset.management_form}}
            {% for field in formset %}

Parts Required:

{{field}}

{{formset}}

            {% endfor %}

        <button class="btn btn-primary" id="add-more" type="button">Add More</button>
        <input class="submit btn btn-primary" type="submit"></input>
    </form>

{% endblock content %}

Here's my view for the warranty form:
# Create Warranty Form:
@login_required(login_url='login')
def createWarranty(request):
    warranty = WarrantyClaim.objects.all()
    form = WarrantyClaimForm()
    warrantyformset = inlineformset_factory(WarrantyClaim, PartsRequired, form=WarrantyClaimForm, extra=1)

    if request.user.is_authenticated:
        if request.method == 'POST':
            form = WarrantyClaimForm(request.POST, request.FILES)
            formset = warrantyformset(request.POST, request.FILES, instance=WarrantyClaim())
            if form.is_valid() and formset.is_valid():
                post = form.save(commit=False)
                post.owner = request.user
                post.save()
                formset.instance = post
                formset.save()
            return redirect('spare-parts')

    context = {'warranty': warranty, 'form': form, 'formset': warrantyformset}
    return render(request, 'spareparts/parts_form.html', context)


text:
Q: Onclick Expand Textbox Width I want to use jQuery to expand the width of a input textbox during onclick.
For example, if the input has a default width of 100px, when the user clicks in it to type, it will expand to like 150px in width.
Is it possible to do this?
Thanks.

A: I'd like to build on @wsanville's example by removing the extra step on saving the original size. Animation also takes string values like '+=50' or '-=50' for increasing/decreasing the width.
See in in action on jsfiddle
$('#box').focus(function()
{
    $(this).animate({ width: '+=50' }, 'slow');
}).blur(function()
{
    $(this).animate({ width: '-=50' }, 'slow');
});

A: I know this is a bit late to the party, but if anyone wants a pure CSS solution that uses the :focus attribute.
#textbox {
  width:100px;
  transition: 0.5s;
}

#textbox:focus {
  width:150px;
  transition: 0.5s;
}

Here's my jsFiddle:
https://jsfiddle.net/qo95uquv/
Tom

A: Here a working example based on @wsanville's example with the requested delay. (Note I also added an effect to return it on loss of focus, you can remove that easily)
Working Example
**edited the size of the textbox

A: Here's an updated example on jsfiddle that animates, and returns to the default size on blur.
For reference, see jQuery Animate docs.

A: <input type="text" id="tbText" size="30px"/>

<script type="text/javascript">
    $(document).ready(function() {
        $('#tbText').focus(function() {
            $('#tbText').css("width", "250px");
        });
        $('#tbText').blur(function() {
            $('#tbText').css("width", "150px");
        });
    });
</script>

A: sure. Lets say you have
<input id="mytextbox" />

you can do
$("#mytextbox").focus(function(){
   $(this).width(150)
});


text:
Q: How to avoid this undesired vertical space in the IEEEtran table environment? I need to collect some tables in one table environment and use the standard \caption command to caption each of them.  My MWP:
\documentclass[letterpaper,twoside,journal,twocolumn,10pt,final]{IEEEtran}%
\usepackage{graphicx}%
\begin{document}%

\title{Sophisticated Table Test}
\author{Author Author}
\IEEEpubid{0000--0000/00\$00.00~\copyright~20XX IEEE}
\maketitle

\begin{table*}[t]
\caption{Top Two-Column Table A}%
\includegraphics[viewport=0pc 0pc 43pc 5pc, clip=true, draft]{sizetest-texpica}%
\caption{Top Two-Column Table B}%
\includegraphics[viewport=0pc 0pc 43pc 5pc, clip=true, draft]{sizetest-texpica}%
%%
\vskip 0pt %% <-- could be replaced by \par but anyway results in an undesired extra vspace
%%
\valign{\hsize=\columnwidth#\cr%
\caption{Bottom One-Column Table C}%
\includegraphics[viewport=0pc 0pc 21pc 5pc, clip=true, draft]{sizetest-texpica}\cr%
\noalign{\hfill}%
\caption{Bottom One-Column Table D}%
\includegraphics[viewport=0pc 0pc 21pc 5pc, clip=true, draft]{sizetest-texpica}\cr%
}%\valign
\end{table*}

\end{document}

The result tables are aligned the following (excerpt from page 2 of the MWP) :

My problem is the extra vertical space added between the body of table B and the captions of tables C and D.  My questions are:

*

*How can i avoid this space? (i need the same space as between the body of table A and the caption of table B)

*If i cannot avoid it, how can at least compensate it using strict, meaningful measures, not a guessing?

*That is the source (cause) of this extra space? Why such a space is avoided between tables A and B, but not between tables B and C/D?
Beforehand thanks.


text:
Q: Loading content from plist to NSDictionary not working I have a rather large plist that I am trying to load data from. Here is an example of the plist, but there are 580 records so I can't put them all here:
<plist version="1.0">
    <array>
            <dict>
                    <key>Grave #</key>
                    <string></string>
                    <key>Last Name</key>
                    <string>?</string>
                    <key>First Name</key>
                    <string>Ada Lou daughter of</string>
                    <key>Dates</key>
                    <string>?-? Unable to read stone</string>
                    <key>Notes</key>
                    <string></string>
                    <key></key>
                    <string></string>
            </dict>
            <dict>
                    <key>Grave #</key>
                    <string></string>
                    <key>Last Name</key>
                    <string>?</string>
                    <key>First Name</key>
                    <string>Stone w/ Cherokee syllabry and also in english says: Here we rest</string>
                    <key>Dates</key>
                    <string></string>
                    <key>Notes</key>
                    <string></string>
                    <key></key>
                    <string></string>
            </dict>

I have my property in my .h file
@property (nonatomic, strong) NSDictionary *graves;

Synthesized in my .m file:
@synthesize graves;

Here is my code that loads the file in my view did load function:
NSString *file = [[NSBundle mainBundle] pathForResource:@"RossCemeteryList" ofType:@"plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:file]) {
    NSLog(@"The file exists");
} else {
    NSLog(@"The file does not exist");
}

graves = [[NSDictionary alloc] initWithContentsOfFile:file];
NSLog(@"%i", [graves count]);

The NSLog messages says it finds the file, the there are 0 rows in the second NSLog message. I can try to spit out the contents graves using "NSLog (@"%@", graves);" and it returns NULL.
I am a little lost. Any help appreciated.

A: You are trying to create an NSDictionary object and initialize it from the contents of that plist while that plist actually contains an NSArray as its root object. You need to change your NSDictionary into an NSArray or NSMutableArray.

A: I don't know if you're still looking for a solution, but this code should allow you to load a plist file and determine the type of its contents:
//  load a Property List ("plist") file (fully-qualified path) into a generic object, if
//  it's available...
- ( NSObject * ) testLoadPListData: ( NSString * const ) plistPath

{

    //  load the file data into a raw data object...
    NSData * const data = [ NSData dataWithContentsOfFile: plistPath ];

    //  fields returned from property list creation...
    NSPropertyListFormat fmt = 0;
    NSError * err = nil;

    //  load the file data into a serialized property list object...
    NSPropertyListSerialization * plist = [ NSPropertyListSerialization propertyListWithData: data
                                                                                options: NSPropertyListImmutable
                                                                                format: &fmt
                                                                                error: &err
                                          ];

    //  if there was an error creating the serialized object...
    NSString * const errorText = err ? [ err description ] : nil;
    if ( errorText )

        {

        //  log the error string...
        NSLog( @"error while reading data from file \"%@\": %@"
             , plistPath
             , errorText
             );

        }  // end error creating serialized object

#if defined( DEBUG )

    //////////////////////////////
    //                          //
    //  DEBUG PURPOSES ONLY...  //
    //                          //
    //////////////////////////////

    //  if this file is in a format that can be readily translated into one of our target data types...
    if (  plist )

        {

        //  if this property list file contains a dictionary...
        if ( [ plist isKindOfClass: [ NSDictionary class ] ] )

            {

            //  dump the contents of the dictionary to the debug output window...
            NSDictionary * const dict = ( NSDictionary * )( plist );
            __CCLOG( @"<Dictionary>%@\n</Dictionary>", dict );

            }  // end is dictionary plist file

        //  if this property list file contains an array...
        else if ( [ plist isKindOfClass: [ NSArray class ] ] )

            {

            //  dump the contents of the array to the debug output window...
            NSArray * const arr = ( NSArray * )( plist );
            __CCLOG( @"<Array>%@</Array>", arr );

            }  // end is array plist file

        }  // end valid file format

#endif  // defined( DEBUG )

    return plist;

}  //  end testLoadPListData


text:
Q: Change HTML Page Language I want to make a page in English that has a button which can change the language to German. I have read thousands of articles about this topic but I haven't got the answer. I know for sure I don't want to make it with Google Translator API or any API. I want to make it with pure JS. I just want to how do you do it? With a button that has a lot of lines that changes the element's text one by one:
function changeLang () { document.getElementById('someid').innerHTML = "some German text"; ... }
Or make it with const transLang { from = "en" to = "de" ...} ?
Please let me know if you have any idea how to start it.

A: For a "pure JS" solution, in other words none of the usual solutions:

*

*no Ajax to get the translated page text / replacement html

*no redirect to a different page which can handle layout incongruities

one option is to store the translations on each div and switch them over using .text().  Do not code your translations into your javascript as that will quickly become impossible to maintain.

function switchLang(lang)
{
    $("[data-" + lang + "]").text(function(i, e) {
        return $(this).data(lang);
    });
}

switchLang("en");

$(".switchlang").click(function() {
    // change the button caption here, eg a flag
    // UX opinion of whether it should be what it is
    // or what it will become
    // ie "de" click to make it "de"
    // or "de" it's currently "de", click to change it
    $(this).text($(this).data("lang"));

    // switch to other language based on language on the button
    var lang = $(this).data("lang") == "de" ? "en" : "de";
    $(this).data("lang", lang);
    switchLang(lang)
});

,

<button class='switchlang' data-lang="en">de</button>

You can then easily add new languages without needing to change any code (this time with separate buttons)

var defaultlang = "en";

function switchLang(lang)
{
    $("[data-" + lang + "]").text(function(i, e) {
        return $(this).data(lang);
    });
}

switchLang("en");

$(".switchlang").click(function() {
    switchLang($(this).data("lang"))
});

,

<button class='switchlang' data-lang="en">en</button>
<button class='switchlang' data-lang="de">de</button>
<button class='switchlang' data-lang="es">es</button>

You may prefer to default the language in the HTML directly, rather than on startup, eg:
save

then store the original in .data("en") on load.  This would remove the FOUC (delay when loading the page) which may be important for your scenario.


text:
Q: How to read a txt file that contains different tables in it I have to collect data in R, that has been given to me in a xls format, but when I open it with Excel it says that the extension and the format don't match, the file suggests I should save it as a .txt file.
The file I have to use typically contains 3 sections, with different tables in them, which have different sizes and column names. The sections are announced by a title between square brackets. This is a simplified version of my file.
I am only interested in the third section, called '[DATA]'. So far I have manually saved it as an xlsx file and worked my way to use the data I was interested in using read_excel. After reading the whole sheet in R I collected the row where the title '[DATA]' was (it can vary from file to file, I can't select a row number as in readLines), then I could select the table underneath after taking the column names (T, Time, Tension etc.) as my new dataframe's column names. I'd like to be able to do something similar starting from a txt file, because I have a lot of files to work with and they are formatted exactly the same way.
I've tried several functions to read the file as a .txt, like
1A = data.table::fread(file, header = F, fill=F, sep = '\t')
2) A = read.delim(file)
3)A = data.frame(readLines(file))
4) A = read.table(file)

*

*It saves the first table from SETUP and stops early, with this error message  "Stopped early on line 25. Expected 24 fields but found 1. Consider fill=TRUE and comment.char=. First discarded non-empty line: <<Number of Duts: 24>>" . If I type fill = TRUE I get the same result as 3.

*It makes a big column of all the cells, line after line and cell by cell.  It becomes difficult to rearrange the data in a table from there.

*It makes a big column again but each line of the file is a cell in the dataframe, and the content of the cell is a string of all the numbers, separated by \t . Example for line 8: experiment1\group1\t0\t7200\t0.001\t"

*I get this error message :  Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 4 did not have 2 elements
I don't know which of these functions is the best lead for this task.
NB : The numbers dispayed in the error messages might be different of what I would get with the example, but I don't even get the error messages with the example (when i made it, Excel required me to put an apostrophy in the cell so the 'minus' sign wouldn't be seen as a formula, so I did. I then saved the file in txt and xls, and even added the xls extension to the txt file to create an incoherence of extension like in my original file. It works in any case.)
Thanks for your help !

A: You said text file and show a spreadsheet, so I'll demonstrate on a multi-table CSV file:
csvtext <- '[SETUP]
ExpName:
GroupName:
,,
Experiment,Group,Voltage
1,1,1
2,2,2
3,3,3
,,
[RESULT]
Group,Dev,V3
1,1,1
3,3,3
4,4,4
,,
[Data]
"mpg","cyl","disp"
21,6,160
21,6,160
22.8,4,108
'

Read it in as text:
# you may use something like
# rawtext <- readLines("path/to/file.csv")
rawtext <- readLines(textConnection(csvtext))
str(rawtext)
#  chr [1:21] "[SETUP]" "ExpName:" "GroupName:" ",," "Experiment,Group,Voltage" "1,1,1" "2,2,2" "3,3,3" ",," "[RESULT]" ...

We can now split the data based on the "empty" lines, then drop these empty lines:
spltext <- split(rawtext, cumsum(!grepl("[^,\\s]", rawtext)))
spltext <- lapply(spltext, function(z) if (grepl("[^,\\s]", z[1])) z else z[-1])
str(spltext)
# List of 5
#  $ 0: chr [1:3] "[SETUP]" "ExpName:" "GroupName:"
#  $ 1: chr [1:4] "Experiment,Group,Voltage" "1,1,1" "2,2,2" "3,3,3"
#  $ 2: chr [1:5] "[RESULT]" "Group,Dev,V3" "1,1,1" "3,3,3" ...
#  $ 3: chr [1:5] "[Data]" "\"mpg\",\"cyl\",\"disp\"" "21,6,160" "21,6,160" ...
#  $ 4: chr(0)

(Note that the $ 0 indicates that the name is "0" not 0, so we'll need to use string-numbers for indexing later.)
From here, since you only want the [Data] section, then
read.csv(text = spltext[["3"]][-1])
#    mpg cyl disp
# 1 21.0   6  160
# 2 21.0   6  160
# 3 22.8   4  108

A: I made it work on any of my files (txt) doing this :
rawtext <- readLines(file)
#separation of the sections with an empty line between them
spltext <- split(rawtext, cumsum(!grepl("[^,\t]", rawtext)))
#removing the cells coded by a former empty line \t
spltext <- lapply(spltext, function(z) if (grepl("[^,\t]", z[1])) z else z[-1])
#The column indexed by 3 is the one that contains the DATA table
data=read.delim(text = base[["3"]][-1], header= T, check.names=F) #check.names= F doesn't affect the titles


text:
Q: Google Visualization: Create Data View from Filtered Table Is there an 'built in' way to create a data view from a dashboard table using only the visible rows? I want to know before I code an unnecessarily long winded alternative!
Edit:
I missed this in the Reference docs but it doesn't completely solve the problem since you still have to do some jiggery pokery to get the status of the active filters on the dash and pass them to the getFilteredRows() method.
You can use the getFilteredRows() method which "Returns the row indexes for rows that match all of the given filters. The indexes are returned in ascending order. The output of this method can be used as input to DataView.setRows()"
https://developers.google.com/chart/interactive/docs/reference#DataView

A: The ChartWrapper object you need to wrap the Table in when using a Dashboard has a "view" parameter you can use to define the DataView you want to use for that chart:
var table = new google.visualization.ChartWrapper({
    chartType: 'Table',
    containerId: 'myTableDiv',
    options: {
        // table options
    },
    view: {
        columns: [/* columns used for the view */]
    }
});

A: For the benefit of anyone who might find this useful, here is the how I solved my problem:
First, create an array of control states from dashboard
control_states = [ctrl1.getState(),ctrl2.getState(),ctrl3.getState()];

Next, create array of all selections for each control
var filteredrows = [ ];
var cnt = 0;
for (var i = 0; i < control_states.length; i++) {
  var picker_state = control_states[i]
  for (var j = 0; j < picker_state.selectedValues.length; j++) {
    filteredrows[cnt] = [ ];
    filteredrows[cnt]["column"] = i;
    filteredrows[cnt]["value"] = picker_state.selectedValues[j];
    cnt += 1;
  };
};

Create new dataview and pass filteredrows array to setRows method:
var filterdata = new google.visualization.DataView(data)
filterdata.setRows(
  filterdata.getFilteredRows(filteredrows)
);


text:
Q: Using regex to match beginning and end of string [Java] I have a list of files in a folder:
maze1.in.txt
maze2.in.txt
maze3.in.txt

I've used substring to remove the .txt extensions.
How do I use regex to match the front and the back of the file name?
I need it to match "maze" at the front and ".in" at the back, and the middle must be a digit (can be single or double digit).
I've tried the following
if (name.matches("name\\din")) {
    //dosomething
}

It doesn't match anything. What is the correct regex expression to use?

A: Your original solution doesn't work because string "name" is not in your text. It is "maze".
You can try this
name.matches("maze\\d{1,2}\\.in")

d{1,2} is used to match a digit(can be single or double digit).

A: I'm a little confused what you are asking for in particular
    ^(maze[0-9]*\.in)$

This will match  maze(any number).in
 ^(maze[0-9]*\.in)\.txt$

this will match maze(any number).in.txt -- excludes the .txt NO NEED FOR USING SUB STRING!
Edit live on Debuggex
The think i would be wary about as of right now is the capture groups... I'm not particularly sure what you are doing with this regex. However, I believe explaining capture groups could benefit you.
A capture group for instance is denoted by () this is basically store them in the pattern array and is a way to parse stuff.
example maze1.in.txt
So if you want to capture the entire line minus .txt i would use this ^(maze[0-9]*\.in\.txt)$
However, if I wanted to capture things separately I would do this ^(maze)([0-9]*)(\.in)\.txt$ this will exclude .txt but include maze, the number, and .in IN separate indexes of the pattern array.

A: You need regex anchors that tell the regex to
start at the beginning: ^
and signal the end of the string: $
^maze[\d]{0,2}\.in$

or in Java:
name.matches("^maze[\\d]{0,2}\\.in$");

Also, your regex wasn't matching strings with a dot (.) which would not accept your examples given.  You need to add \. to the regex to accept dots because . is a special character.

A: It is always good to think of what you are trying to do in english, before you create regular expressions.
You want to match a word maze followed by a digit, followed by a literal period . followed by another word.
word   `\w` matches a word character
digit  `\d` matches a single digit
period `\.` matches a literal period
word   `\w` matches a word character

putting it all together into a single string you get (keep in mind the double backslash for the Java escape and the pluses to repeat the previous match one or more times):
"\\w+\\d\\.\\w+"

The above is the generic case for any file name in the format xxx1.yyy, if you wanted to match maze and in specifically, you can just add those in as literal strings.
"maze\\d+\\.in"

example: http://ideone.com/rS7tw1

A: name.matches("^maze[0-9]+\\.in\\.txt$")


text:
Q: Jenkins : Where does Jenkins store configuration files for the assigned users(ldap user)? I set the LDAP into Jenkins and assigned some users. Now, is anybody knows where Jenkins stores all these info? I checked in config.xml but didn't found. (It have the ldap setting but not the users list)
I logged myself out now so can't use Jenkins UI. I think I have to enable the admin again in that list.

A: First, check if this article could help

Edit the config.xml file in the JENKINS_HOME folder and locate this line:
<useSecurity>true</useSecurity>

Set it to false, and restart Jenkins.
Users are, on first login, created/stored under JENKINS_HOME/users (see this article for illustration)

A: Jenkins does not support LDAP and local user list together, see also this feature request. By enabling LDAP you disabled your local user configuration.


text:
Q: Polymer app-router problems Hopefully somebody can help me better understanding using app-router with Polymer. I have the following files - index.html, app.html and updates.html.
Everything is working as it should with the main layout appearing when I navigate to the root of the domain but nothing appears in the content area where I am trying to render the contents of the updates.html file using the app-router element.
Any help is much appreciated
index.html

  <title>Example App</title>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">

  <link rel="stylesheet" href="styles/main.css">

  <link rel="import" href="elements/app.html">

  <example-app></example-app>

app.html
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/core-icons/core-icons.html">
<link rel="import" href="../bower_components/core-item/core-item.html">
<link rel="import" href="../bower_components/core-scaffold/core-scaffold.html">
<link rel="import" href="../bower_components/core-toolbar/core-toolbar.html">
<link rel="import" href="../bower_components/core-menu/core-menu.html">
<link rel="import" href="../bower_components/app-router/app-router.html">

<polymer-element name="example-app">
  <template>
    <core-scaffold id="scaffoldPanel">
      <core-header-panel navigation flex>
        <core-toolbar id="navheader" class="tall">

        </core-toolbar>
      </core-header-panel>

      <core-toolbar tool flex>

Example App

          <core-icon icon="search"></core-icon>
      </core-toolbar>

        <app-router>
          <app-route path="/" import="elements/updates.html" element="app-updates"></app-route>
        </app-router>

    </core-scaffold>
  </template>
</polymer-element>

updates.html
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="app-updates">
  <template>

UPDATES

Updates appear here

  </template>
</polymer-element>


text:
Q: My cursor changes color and size when I click I have a 4k display attached to my laptop's builtin 1920x1080 display.
I have to use LightDM because my external monitor was not working with GDM.
When I don't click on anything my cursor is large and white in color like this:

When I click it gets smaller and turns black like this:

This happens regardless of the screen I am using at the time.
Is there a way to get the cursor to not change size and color?


text:
Q: Why isn't the "this." command needed in this constructor? (java) I'm reading a book about java. It just got to explaining how you create a class called "deck" which contains an array of cards as its instance variable(s). Here is the code snippit:
class Deck {
    Card[] cards;
    public Deck (int n) {
        cards = new Card[n];
    }
}

why isn't the this. command used?
for example why isn't the code this:
class Deck {
    Card[] cards;
    public Deck (int n) {
       this.cards = new Card[n];
    }
}

A: You do not need to qualify all access to members with the this keyword. You only need to use it whenever another variable is hiding the member method.
And that is not a feature limited to the constructor, but available in all methods:
public class Test
{
   private int member;
   private int value;
   public Test(int value) {
      member = 5;
      this.value = value; // required to differentiate from the parameter
   }
   public void f( int member ) {
      int value = 5
      this.member = value; // assign local 'value' (5) to member 'member'
      this.value = member; // assign parameter 'member' to member 'value'
   }
}

A: The object's this reference is implied, but it can be useful for clarity (and it's necessary for disambiguation between an object's member and a local variable of the same name, as in the constructor below):
   public class Foo {
       final private int x;

       public Foo(int x) { this.x = x; }

       public int getX() { return this.x; }
   }

A: When you use the identifier cards in the constructor, the compiler notices that the field (a.k.a. member variable) cards is in scope, and uses it.  this.cards would only be necessary to resolve ambiguities, for instance if you also had a local variable or parameter named cards.

A: It would have sense if you also have a parameter named cards. Then this.cards would specify that you mean exactly field cards of class, not the parameter.
But anyway it's counted a good practice to use this. in cases as described in your example.

A: Because there is no ambiguity. There is only one cards variable. this would be needed if there were two - one of which being an instance variable (part of the class, as it currently is), and the other - an argument of the constructor.
And btw, this isn't a "command". It's a "keyword".

A: This is implied.
Let's elaborate:
class Deck {
     Card[] cards;
     public Deck (Card[] cards) {
          this.cards = cards;
     }
}

In this case you pass in an array of cards that shares the same name as the object's array of cards.  This refers to your object's datamember, not the constructor's parameter.

A: this. is implicit.
In general, it's a best practice (at least I consider it one) to only use this when absolutely necessary. When you have a local variable named cards and a member variable named cards, for example, you'll need this.cards to refer to the member variable, as cards refers to the local variable.
In such a case, this is a good idea (although it might be a better idea to rename the member variable).
In every other case, where an implicit this can work, use it.

A: The "this" keyword is redundant in that case. cards is already defined at class scope and the complier knows that the member is part of "this" class.

A: "this" is implied. There is no need to use "this". I usually put it there just to make the code readable, but again it's not required.

A: I try to select variable names in a way that doesn't require the "this" keyword.  That is, if I have a property named "value", I will pass to a parameter called val.
A good use of the "this" keyword is for constructor overloading.  Consider the following (I will use this. to demonstrate the difference):
public class Person
{
   int age;
   public Person(int age)
   {
      this.age=age;
   }
   public Person()
   {
      this(25); //default age
   }
}

When at all possible, I will try to avoid having the property and parameter name the same to avoid what you see on line 6.  However, the use of the this keyword for calling another constructor is a good way to prevent code duplication.  This is a trivial example, but when you start finding yourself with constructors that do a lot of the same work with small differences between them, it comes in quite handy.