text:
Q: Implicit return values in Ruby I am somewhat new to Ruby and although I find it to be a very intuitive language I am  having some difficulty understanding how implicit return values behave.
I am working on a small program to grep Tomcat logs and generate pipe-delimited CSV files from the pertinent data. Here is a simplified example that I'm using to generate the lines from a log entry.
class LineMatcher
  class << self
    def match(line, regex)
      output = ""
      line.scan(regex).each do |matched|
        output << matched.join("|") << "\n"
      end
      return output
    end
  end
end

puts LineMatcher.match("00:00:13,207 06/18 INFO  stateLogger - TerminationRequest[accountId=AccountId@66679198[accountNumber=0951714636005,srNumber=20]",
                       /^(\d{2}:\d{2}:\d{2},\d{3}).*?(\d{2}\/\d{2}).*?\[accountNumber=(\d*?),srNumber=(\d*?)\]/)

When I run this code I get back the following, which is what is expected when explicitly returning the value of output.
00:00:13,207|06/18|0951714636005|20

However, if I change LineMatcher to the following and don't explicitly return output:
    class LineMatcher
      class << self
        def match(line, regex)
          output = ""
          line.scan(regex).each do |matched|
            output << matched.join("|") << "\n"
          end
        end
      end
    end

Then I get the following result:
00:00:13,207
06/18
0951714636005
20

Obviously, this is not the desired outcome. It feels like I should be able to get rid of the output variable, but it's unclear where the return value is coming from. Also, any other suggestions/improvements for readability are welcome.

A: Any statement in ruby returns the value of the last evaluated expression.
You need to know the implementation and the behavior of the most used method in order to exactly know how your program will act.
#each returns the collection you iterated on. That said, the following code will return the value of line.scan(regexp).
line.scan(regex).each do |matched|
  output << matched.join("|") << "\n"
end

If you want to return the result of the execution, you can use map, which works as each but returns the modified collection.
class LineMatcher
  class << self
    def match(line, regex)
      line.scan(regex).map do |matched|
        matched.join("|")
      end.join("\n") # remember the final join
    end
  end
end

There are several useful methods you can use depending on your very specific case. In this one you might want to use inject unless the number of results returned by scan is high (working on arrays then merging them is more efficient than working on a single string).
class LineMatcher
  class << self
    def match(line, regex)
      line.scan(regex).inject("") do |output, matched|
        output << matched.join("|") << "\n"
      end
    end
  end
end

A: In ruby the return value of a method is the value returned by the last statement. You can opt to have an explicit return too.
In your example, the first snippet returns the string output. The second snippet however returns the value returned by the each method (which is now the last stmt), which turns out to be an array of matches.
irb(main):014:0> "StackOverflow Meta".scan(/[aeiou]\w/).each do |match|
irb(main):015:1* s << match
irb(main):016:1> end
=> ["ac", "er", "ow", "et"]

Update: However that still doesn't explain your output on a single line. I think it's a formatting error, it should print each of the matches on a different line because that's how puts prints an array. A little code can explain it better than me..
irb(main):003:0> one_to_three = (1..3).to_a
=> [1, 2, 3]
irb(main):004:0> puts one_to_three
1
2
3
=> nil

Personally I find your method with the explicit return more readable (in this case)


text:
Q: READ and WRITE external storage permissions gets added when not specified in manifest file I am trying to upload my app to the Google Play store.
The app was created using Xamarin Forms.
After I upload, READ ACCESS EXTERNAL STORAGE and WRITE ACCESS EXTERNAL STORAGE.
I have checked my manifest file and neither 'write' nor 'read' is checked in it.
Can it be because of any nugget packages that might require external storage?
Details:

*

*min android version - 4.3

*install location - internal only

*Target android version - API 24 (automatic)
Thanks.

A: I had the same problem. Removing this line from AssemblyInfo.cs fixed it.
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tensorflow Lite Micro package in Keil custom MCU platform I have tried to use tflite default package in Keil MDK environment, but I am facing some compiling problems.
project code
My Device: Armv8-M Mainline based device
My TFlite runtime environment:
runtime environment
There are hundreds of errors existed.
error type1
error: use of undeclared identifier 'EAFNOSUPPORT'/.../...
error type2
error: use of undeclared identifier 'errno'
What's maybe going wrong?
I tried to compile the package in an empty project with the same environment settings, and it could be compiled instead of such as errors.

A: I solved the problem by disabling the redefined symbol in ROM.lib file.


text:
Q: How to iterate uneven arrays? here i have two uneven arrays(size of array is not equal),  i have to append insert when the arr1  numbers matches in arr2.but when condition become false the zero should only add one time instead of repeating. below is the code
arr2 =[     [[27, 28, 29, 30, 31, 1, 2], 5],
            [[31, 1, 2, 3, 4, 5, 6], 14],
            [[26, 27, 28, 29, 30, 31, 1], 22],
            [[28, 29, 30, 31, 1, 2, 3], 31],
            [[25, 26, 27, 28, 29, 30, 31], 35],
            [[27, 28, 29, 30, 31, 1, 2], 44],
            [[29, 30, 31, 0, 0, 0, 0], 53]
            ]
arr1 = [5, 0, 14, 0, 22, 0, 31, 35, 0, 44, 0, 53]

cc = []
arr1.each do|item_arr1|
    arr2.each_with_index do|item_arr2,index|
        if item_arr1 == arr2[index][-1]
            cc << item_arr2
        else
            cc << 0
        end
    end
end

output:
[
  [ [27, 28, 29, 30, 31, 1, 2], 5 ],
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  [ [31, 1, 2, 3, 4, 5, 6], 14 ],
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  [ [26, 27, 28, 29, 30, 31, 1], 22 ],
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  [ [28, 29, 30, 31, 1, 2, 3], 31 ],
  0, 0, 0, 0, 0, 0, 0,

  [ [25, 26, 27, 28, 29, 30, 31], 35 ],
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  [ [27, 28, 29, 30, 31, 1, 2], 44 ],
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  [ [29, 30, 31, 0, 0, 0, 0], 53 ]
]

Expected output:
[
  [ [27, 28, 29, 30, 31, 1, 2], 5 ], 0,

  [ [31, 1, 2, 3, 4, 5, 6], 14 ], 0,

  [ [26, 27, 28, 29, 30, 31, 1], 22 ], 0,

  [ [28, 29, 30, 31, 1, 2, 3], 31 ],

  [ [25, 26, 27, 28, 29, 30, 31], 35 ], 0,

  [ [27, 28, 29, 30, 31, 1, 2], 44 ], 0,

  [ [29, 30, 31, 0, 0, 0, 0], 53 ]
]

A: Assuming that the numbers are unique, you could use rassoc to fetch the sub-array from arr1:
arr1.map { |i| arr2.rassoc(i) || i }
#=> [
#     [[27, 28, 29, 30, 31, 1, 2], 5], 0,
#     [[31, 1, 2, 3, 4, 5, 6], 14], 0,
#     [[26, 27, 28, 29, 30, 31, 1], 22], 0,
#     [[28, 29, 30, 31, 1, 2, 3], 31],
#     [[25, 26, 27, 28, 29, 30, 31], 35], 0,
#     [[27, 28, 29, 30, 31, 1, 2], 44], 0,
#     [[29, 30, 31, 0, 0, 0, 0], 53]
#  ]

A: This is not very Ruby-like but it should be relatively efficient because it avoids the need to search arrays.
a1 = arr1.size.times.with_object([]) do |i,a|
  n = arr1[i]
  next if n.zero?
  a << (i < arr1.size-1 && arr1[i+1].zero?)
end
  #=> [true, true, true, false, true, true, false]

A zero should be inserted after arr2[i] if a1[i] is true.
arr2.each_with_object([]) do |a2,a|
  a << a2
  a << 0 if a1.shift
end
  #=> [
  #    [[27, 28, 29, 30, 31, 1, 2], 5], 0,
  #    [[31, 1, 2, 3, 4, 5, 6], 14], 0,
  #    [[26, 27, 28, 29, 30, 31, 1], 22], 0,
  #    [[28, 29, 30, 31, 1, 2, 3], 31],
  #    [[25, 26, 27, 28, 29, 30, 31], 35], 0,
  #    [[27, 28, 29, 30, 31, 1, 2], 44], 0,
  #    [[29, 30, 31, 0, 0, 0, 0], 53]
  #   ]


text:
Q: Ubuntu Linux freezes after boot up After a fresh installation of Ubuntu Linux 11.04 under Lenovo G570, when I choose Ubuntu Linux 11.04 in grub menu, Ubuntu freezes in a black screen and even hiting ctrl+alt+f1-f10 didn't make any difference. Is there any suggestion that I can find out what's the problem ?

A: Boot from a LiveCD, mount the hard drive so you can access it, then navigate to the logs.


text:
Q: Am I supposed to pass around Pino child loggers? This is rather a stylistic question. I'm using Pino in some of my Javascript/Typescript microservices. As they're running on AWS I'd like to propagate the RequestId.
When one of my functions is invoked, I'm creating a new child logger like this:
const parentLogger = pino(pinoDefaultConfig)

function createLogger(context) {
  return parentLogger.child({
    ...context,
  })
}

function createLoggerForAwsLambda(awsContext) {
  const context = {
    requestId: awsContext.awsRequestId,
  }
  return createLogger(context)
}

I'm then passing down the logger instance to all methods. That said, (... , logger) is in almost every method signature which is not too nice. Moreover, I need to provide a logger in my tests.
How do you do it? Is there a better way?

A: you should implement some sort of Dependency Injection and include your logger there.
if your using microservices and maybe write lambdas in a functional approach, you can handle it by separating the initialization responsibility in a fashion like this:
import { SomeAwsEvent } from 'aws-lambda';
import pino from 'pino';

const createLogger = (event: SomeAwsEvent) => {
  return pino().child({
    requestId: event.requestContext.requestId
  })
}

const SomeUtil = (logger: pinno.Logger) => () => {
  logger.info('SomeUtil: said "hi"');
}

const init(event: SomeAwsEvent) => {
  const logger = createLogger(event);
  someUtil = SomeUtil(logger);

  return {
    logger,
    someUtil
  }
}

export const handler = (event: SomeAwsEvent) => {
  const { someUtil } = init(event);

  someUtil();

  ...
}

A: The simplest way is to use some DI library helper to tackle this
import { createContainer } from "iti"
interface Logger {
  info: (msg: string) => void
}
class ConsoleLogger implements Logger {
  info(msg: string): void {
    console.log("[Console]:", msg)
  }
}
class PinoLogger implements Logger {
  info(msg: string): void {
    console.log("[Pino]:", msg)
  }
}

interface UserData {
  name: string
}

class AuthService {
  async getUserData(): Promise<UserData> {
    return { name: "Big Lebowski" }
  }
}

class User {
  constructor(private data: UserData) {}
  name = () => this.data.name
}

class PaymentService {
  constructor(private readonly logger: Logger, private readonly user: User) {}
  sendMoney() {
    this.logger.info(`Sending monery to the: ${this.user.name()} `)
    return true
  }
}

export async function runMyApp() {
  const root = createContainer()
    .add({
      logger: () =>
        process.env.NODE_ENV === "production"
          ? new PinoLogger()
          : new ConsoleLogger(),
    })
    .add({ auth: new AuthService() })
    .add((ctx) => ({
      user: async () => new User(await ctx.auth.getUserData()),
    }))
    .add((ctx) => ({
      paymentService: async () =>
        new PaymentService(ctx.logger, await ctx.user),
    }))

  const ps = await root.items.paymentService
  ps.sendMoney()
}

console.log(" ---- My App START \n\n")
runMyApp().then(() => {
  console.log("\n\n ---- My App END")
})

it is easy to write tests too:
import { instance, mock, reset, resetCalls, verify, when } from "ts-mockito"
import { PaymentService } from "./payment-service"
import type { Logger } from "./logger"

const mockedLogger = mock<Logger>()
when(mockedLogger.info).thenReturn(() => null)

describe("Payment service: ", () => {
  beforeEach(() => {
    resetCalls(mockedLogger)
    // reset(mockedLogger)
  })
  it("should call logger info when sending money", () => {
    const paymentService = new PaymentService(instance(mockedLogger))
    expect(paymentService.sendMoney()).toBe(true)
  })
})

A: I would not use the requestId as part of the context of the logger, but use it as the payload of the logger, like logger.info({ requestId }, myLogMessage). This was you can have a simple function create a child logger that you can use for the entire module.


text:
Q: Exception when training data in Predictionio I am trying to Deploy an Recommendation Engine as mentioned in quick start guide.
I completed the steps up to build the engine. Now I want to train the Recommendation Engine. I did as mentioned in quick start guide. (execute pio train). Then I got the lengthy error log and I couldn't paste all here. So I am putting first few rows of the error.
[INFO] [Console$] Using existing engine manifest JSON at /home/PredictionIO/PredictionIO-0.9.6/bin/MyRecommendation/manifest.json
[INFO] [Runner$] Submission command: /home/PredictionIO/PredictionIO-0.9.6/vendors/spark-1.5.1-bin-hadoop2.6/bin/spark-submit --class io.prediction.workflow.CreateWorkflow --jar/PredictionIO/PredictionIO-0.9.6/bin/MyRecommendation/target/scala-2.10/template-scala-parallel-recommendation_2.10-0.1-SNAPSHOT.jar,file:/home/PredictionIO/PredictionIO-0.9.6/bndation/target/scala-2.10/template-scala-parallel-recommendation-assembly-0.1-SNAPSHOT-deps.jar --files file:/home/PredictionIO/PredictionIO-0.9.6/conf/log4j.properties --driver/home/PredictionIO/PredictionIO-0.9.6/conf:/home/PredictionIO/PredictionIO-0.9.6/lib/postgresql-9.4-1204.jdbc41.jar:/home/PredictionIO/PredictionIO-0.9.6/lib/mysql-connector-jav file:/home/PredictionIO/PredictionIO-0.9.6/lib/pio-assembly-0.9.6.jar --engine-id qokYFr4rwibijNjabXeVSQKKFrACyrYZ --engine-version ed29b3e2074149d483aa85b6b1ea35a52dbbdb9a --et file:/home/PredictionIO/PredictionIO-0.9.6/bin/MyRecommendation/engine.json --verbosity 0 --json-extractor Both --env PIO_ENV_LOADED=1,PIO_STORAGE_REPOSITORIES_METADATA_NAME=pFS_BASEDIR=/root/.pio_store,PIO_HOME=/home/PredictionIO/PredictionIO-0.9.6,PIO_FS_ENGINESDIR=/root/.pio_store/engines,PIO_STORAGE_SOURCES_PGSQL_URL=jdbc:postgresql://localhost/pGE_REPOSITORIES_METADATA_SOURCE=PGSQL,PIO_STORAGE_REPOSITORIES_MODELDATA_SOURCE=PGSQL,PIO_STORAGE_REPOSITORIES_EVENTDATA_NAME=pio_event,PIO_STORAGE_SOURCES_PGSQL_PASSWORD=pio,PIURCES_PGSQL_TYPE=jdbc,PIO_FS_TMPDIR=/root/.pio_store/tmp,PIO_STORAGE_SOURCES_PGSQL_USERNAME=pio,PIO_STORAGE_REPOSITORIES_MODELDATA_NAME=pio_model,PIO_STORAGE_REPOSITORIES_EVENTDGSQL,PIO_CONF_DIR=/home/PredictionIO/PredictionIO-0.9.6/conf
[INFO] [Engine] Extracting datasource params...
[INFO] [WorkflowUtils$] No 'name' is found. Default empty String will be used.
[INFO] [Engine] Datasource params: (,DataSourceParams(MyApp3,None))
[INFO] [Engine] Extracting preparator params...
[INFO] [Engine] Preparator params: (,Empty)
[INFO] [Engine] Extracting serving params...
[INFO] [Engine] Serving params: (,Empty)
[WARN] [Utils] Your hostname, test-digin resolves to a loopback address: 127.0.1.1; using 192.168.2.191 instead (on interface p5p1)
[WARN] [Utils] Set SPARK_LOCAL_IP if you need to bind to another address
[INFO] [Remoting] Starting remoting
[INFO] [Remoting] Remoting started; listening on addresses :[akka.tcp://sparkDriver@192.168.2.191:56574]
[WARN] [MetricsSystem] Using default name DAGScheduler for source because spark.app.id is not set.
[INFO] [Engine$] EngineWorkflow.train
[INFO] [Engine$] DataSource: duo.DataSource@6088451e
[INFO] [Engine$] Preparator: duo.Preparator@1642eeae
[INFO] [Engine$] AlgorithmList: List(duo.ALSAlgorithm@a09303)
[INFO] [Engine$] Data sanity check is on.
[INFO] [Engine$] duo.TrainingData does not support data sanity check. Skipping check.
[INFO] [Engine$] duo.PreparedData does not support data sanity check. Skipping check.
[WARN] [BLAS] Failed to load implementation from: com.github.fommil.netlib.NativeSystemBLAS
[WARN] [BLAS] Failed to load implementation from: com.github.fommil.netlib.NativeRefBLAS
[WARN] [LAPACK] Failed to load implementation from: com.github.fommil.netlib.NativeSystemLAPACK
[WARN] [LAPACK] Failed to load implementation from: com.github.fommil.netlib.NativeRefLAPACK
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task serialization failed: java.lang.StackOverflowError
java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
scala.collection.immutable.$colon$colon.writeObject(List.scala:379)
sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)

what can I do to overcome this isssue?

A: Your error says java.lang.StackOverflowError for that you can reduce the numIterations parameter in engine.json file. Refer this.

A: I had a similar issue on an 8GB MacOS machine . Changing the numIterations parameter in /MyRecommendation/engine.json to 10 (used to be 20 by default) solved the issue for me. Using --driver-memory and --executor-memory with pio train did not.


text:
Q: Can't calculate the difference between 2 days in hours I need to check if some date and now arent' different more than in 18 hours:
dt = parser.parse("some date 123") #working well

diff = datetime.datetime.now() - dt
print "datetime.datetime.now() - dt = %s" % diff  # 31 days, 0:08:04.882498 -- correct
print "datetime.datetime.now() - dt seconds = %s" % diff.seconds # 484 -- too

(datetime.datetime.now() - dt).seconds / 3600) < 18 # returns True always

As you can see, even though the dates are different in 31 days, the amount of seconds if very little which doesn't allow me to calculate the amount of hours. Why is it so small? Should it be x * 60 * 60 * amount_of_days? And how can I do what I want?

A: You may try this:
from datetime import date

date0 = date(2014, 9, 07)
date1 = date(2014, 9, 05)
diff = date0 - date1
print diff.days * 24

Also check How do I check the difference, in seconds, between two dates?
or
>>> from datetime import datetime
>>> date0 = datetime(2014,09,07,0,0,0)
>>> date1 = datetime(2014,09,01,23,59,59)
>>> date0-date1
datetime.timedelta(6, 1)
>>> (date0-date1).days * 24
144

A: seconds is returning just the number of seconds, not the total number of seconds, for that you can use timedelta.total_seconds.


text:
Q: How to select/merge multiple matching result? I am trying to create a cascading set of drop-down list, country list based upon the region list.
I have created a Dictionary<String, List<String>> in the code behind, which includes a region, country list.
Now on region drop down selection (which is multi select able),
I need to select the countries belonging to the particular regions(selected ones) and bind it to the country list.
I am trying this way:
List<string> selectedRegions = (from ListItem item in regionList.Items
                                where item.Selected
                                select item.Text).ToList();

var countryList = (selectedRegions
                          .Where(item => regionToCountry.ContainsKey(item))
                          .Select(item => new { value = regionToCountry[item] }));

countryList.DataSource = countryList.ToList();
countryList.DataBind();

The problem is country list gets the result in indexed format like : countryList[0] (contains all the country from region a)
countryList[1] from region B.
I need a merged list which I can bind to the dropdown.
Thanks a lot in advance.
Vishal

A: You can use SelectMany to flatten the List<string> inside the Dictionary<TKey,TValue>.
var countryList =
    regionToCountry.Where(x => selectedRegions.Contains(x.Key))
                   .SelectMany(x => x.Value)
                   .ToList();

A: Try this:
var countryList = selectedRegions
                          .Where(item => regionToCountry.ContainsKey(item))
                          .SelectMany(item => regionToCountry[item])
                          .ToList();


text:
Q: CoreData unique objects by attribute I have a graph with one kind of object called Message. A message could have childs so the graph is a tree.
Each object on the graph contains an attribute value; that's a sort of UUID (globally unique) so the store cannot contains multiple messages with the same UUID (this uuid is a string taken from message data so I can't replace it using the objectID of nsmanagedobject).
The problem happend when I need to validate object insertion into the store.
How can I check if a message with the same UUID is already present into the store? I'm thinking about a fetch request on validateForInsert: event but it seems too slow/complex when there are lots of objects to insert (about 30k in my case).
Anyone have a best solution?

A: This is a known limitation with CoreData (I've filed a feature request on this myself).  You should also go to http://bugreport.apple.com and let them know you want this feature.  (The original bug id is rdar://3711805)
The way I've gotten around this in the past is to use a convenience method to access and create my NSManagedObjects.  This convenience method then looks up in a static NSMutableDictionary to see if another object with the same unique attribute has already been created (the unique attribute being the key, and the managedObjectID being the value).  If it finds one, it just returns that object instead.  If it doesn't, then it goes about creating one and caching that object's ID into the static dictionary for future use.  When the app first launches, I have to pre-populate this dictionary with the attributes/identifiers of pre-existing objects.
It's a pain, I know. :(  File an enhancement request.

A: Okay with a second index results are better, so I try to make a summary of the problem and the solution. If anyone have a better idea I'll be happy to talk about it :)
I've about 30,000 messages taken from network and I need to save all into a Core Data Store in form of a tree.
Each message contains an unique identification string and no more than one message can be saved on database with the same id.
CoreData at this time does not support uniqueness of attributes and I can't use objectID property to ensure this kind of thing.
A first solution is, in pseudo code:
- Execute a query to see if uuid string is presents in storage
- If it's not present I can make a new NSManagedObject with that uuid and put it into storage, otherwise I'll ignore it (it's already on db)
- Execute another query to find the direct parent of this new message, if found I'll link both messages, if not it's a root message
This solution has a big problem. With 30k messages I need of 30k query to check if the new message exist on coredata, another 30k to check for parent (plus, I think, another 30k to insert the new object). Over 60k+ queries takes lots of time (a minute or more here).
My second solution is to create a second auxiliary NSMutableDictionary where i'll save message uuid as key and NSManagedObjectID's URI rapresentation (the only I can save to NSData) as value for dictionary entry.
The result in pseudo code is:
- Use objectForKey:uuid to my auxiliary dictionary to see if the message exist in coredata
- If yes I'll ignore it. If not i'll put it into the store
- Use objectForKey:parentuuid to my auxiliary dictionary to see if the parent of the message is present on coredata. If yes i'll use NSPersistentCoordinator's managedObjectIDForURIRepresentation: to get the NSManagedObject (the parent of the message) and link both parent and child
With this solution the entire process takes about 5 seconds to finish (the result dictionary it's around 2mb).

A: I've uploaded an example project with both two techniques.
Using coredata+indexed attributed takes about 4 minutes to save (what's wrong?!!)
With an auxiliary index it takes about 3 seconds to save.
Feel free to comment it.
It's very strange, especially after I've read it:
http://cocoawithlove.com/2008/03/testing-core-data-with-very-big.html
this is my code project:
http://dl.dropbox.com/u/103260/CoreDataTreeTest2.zip

A: A temp solution (thanks to Roland from Cocoa-dev), if anyone wanna use CoreData, is to save the context each X insertion. In my case using ([ctx save:]) each 500/1000 insertion drop down time from minutes to seconds (another project that implement this solution is available here: http://dl.dropbox.com/u/103260/CoreDataTreeTest3.zip)
These are my benchmarks with 30.000 objects:

*

*CoreData without saving each X
insertions: about 5-6 minutes

*CoreData with saving each 500 insertions: about 30 seconds

*CoreData with auxiliary indexes dictionary: about 2 seconds

However that's seems to be strange.
According to:
http://cocoawithlove.com/2008/03/testing-core-data-with-very-big.html
it should be faster than that, and 30k objects are few objects for CoreData. I would to try to fill a bug at bugreporter and listen what Apple Engineers says.


text:
Q: How data should be visible to user and their sub-user using spring websocket I want to achieve this functionality using sockjs + stomp + spring-boot-websocket as mentioned in image:

A: You have 2 options:
1. Create utility that send message to user and inside you will need to send message to 3 users(User + Sub user) and use this utility inside your controller

*Create dedicated channels that every user and sub user will subscribe into it. You can add security inside the subscribe message if you would like to.

Look below:
MyClassInterceptor  extends ChannelInterceptorAdapter {
private static final Logger LOGGER = LogManager.getLogger(MyClassInterceptor .class);
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {

MessageHeaders headers = message.getHeaders();
SimpMessageType type = (SimpMessageType) headers.get("simpMessageType");
String simpSessionId = (String) headers.get("simpSessionId");

if (type == SimpMessageType.CONNECT) {
    Principal principal = (Principal) headers.get("simpUser");
    LOGGER.debug("WsSession " + simpSessionId + " is connected for user " + principal.getName());
} else if (type == SimpMessageType.DISCONNECT) {
    LOGGER.debug("WsSession " + simpSessionId + " is disconnected");
}
return message;
}
}

Personally i think option one is simplier and doesn't require from you to deal with to many things.
You cannot do it with spring because it create prefix for every user according to user name so every username will have specific queue


text:
Q: C# if else stops code from continuing I have a section of code where I am trying to make it so the user puts in their name and I want it to recognise if it's an actually name. So to keep things simple I just want it to accept letters only.
I type a valid name in and it carries on to the next section of code. However when I put in invalid characters I get the "Invalid Name" message but after that no matter what I type in it just keeps saying "Invalid Name".
Console.WriteLine("Please Enter First Name");
bool isNotName = true;
string firstName = Console.ReadLine();

while (isNotName)
{
    if (Regex.IsMatch(firstName, @"^[a-zA-Z]+$"))
    {
        {
            Console.WriteLine("Welcome {0}", firstName);
        }
        isNotName = false;
    }
    else
    {
        Console.WriteLine("Invalid Name");
        Console.ReadLine();
    }
 }

A: The firstName value is not updated in the loop, so try this :
string firstName = Console.ReadLine();

 while (isNotName)
{
    if (Regex.IsMatch(firstName, @"^[a-zA-Z]+$"))
    {
        {
        Console.WriteLine("Welcome {0}", firstName);
        }
        isNotName = false;
    }

    else
    {
        Console.WriteLine("Invalid Name");
        firstName = Console.ReadLine();
    }
 }

A: Console.WriteLine("Please Enter First Name");
bool isNotName = true;
string firstName = Console.ReadLine();

while (isNotName)
{
    if (Regex.IsMatch(firstName, @"^[a-zA-Z]+$"))
    {
        Console.WriteLine("Welcome {0}", firstName);
        isNotName = false;
    }
    else
    {
        Console.WriteLine("Invalid Name");
        firstName = Console.ReadLine(); // <---- re-assign name here
    }
}

Also I would refactor your code to remove boolean flag:
Console.WriteLine("Please Enter First Name");
string firstName = Console.ReadLine();

while(!Regex.IsMatch(firstName, @"^[a-zA-Z]+$"))
{
    Console.WriteLine("Invalid Name");
    firstName = Console.ReadLine();
}

Console.WriteLine("Welcome {0}", firstName);

A: Your issue is here in the else part of the conditional:
Console.ReadLine();

It should be:
firstName = Console.ReadLine();

What's happening is that you're saving the user input the first time you read input from the console but not saving it in subsequent calls to ReadLine()
i.e. your code should be:
Console.WriteLine("Please Enter First Name");
bool isNotName = true;
string firstName = Console.ReadLine();

while (isNotName)
{
    if (Regex.IsMatch(firstName, @"^[a-zA-Z]+$"))
    {
        Console.WriteLine("Welcome {0}", firstName);
        isNotName = false;
    }
    else
    {
        Console.WriteLine("Invalid Name");
        firstName = Console.ReadLine();
    }
}

A: You read the name once.
Use string firstName = Console.ReadLine(); at the begining of the while loop.

A: Try this in your else part
else
{
firstName = Console.ReadLine();
}

A: You are not setting the firstName variable in the subsequent readline:
   Console.WriteLine("Invalid Name");
   firstName = Console.ReadLine();

A: Just to try to be original, your peers would probably enjoy reading something like this:
string firstName;
while (!(Regex.IsMatch(firstName = Console.ReadLine(), @"^[a-zA-Z]+$")))
{
    Console.WriteLine("Invalid Name");
}

Console.WriteLine("Welcome {0}", firstName);

It's just for lulz though, assignment inside a conditional expression is always a bad idea. :)

A: The bug is that the value of firstName is never updated.
The code can be improved:
Console.WriteLine("Please Enter First Name");
string firstName = Console.ReadLine();
While (!Regex.IsMatch(firstName, @"^[a-zA-Z'-]+$")) {
    Console.WriteLine("Invalid Name");
    firstName = Console.ReadLine();
}
Console.WriteLine("Welcome {0}", firstName);


text:
Q: Upgrading Git Bash to run newly downloaded ruby 2.0.0 I'm on a Windows machine, so unfortunately I can't use RVM, which would make this super easy.
I previously downloaded Rails and Ruby on a new Windows machine. Rails 4.0.3 and Ruby 1.9.3. For some reason, the package I installed didn't install the new version of ruby. So I just went to http://rubyinstaller.org/downloads/ and downloaded Ruby 2.0.0. If I browse to my Apps to access the Start Command Prompt with Ruby, the version is 2.0.0 (ruby -v). But I use Git Bash, http://git-scm.com/downloads, as my Command Line. Right now, the current ruby version is still 1.9.3 in my Git Bash window. How do I update it to use the newly downloaded Ruby 2.0.0???
Thanks for the help.

A: Issuing
$ which ruby

will tell you which of the two ruby executables GIT Bash wants to use.
For situations where it is necessary to have two versions of Ruby, it's possible to select one or other for general use using the PATH environment variable.
The order of paths in the Bash $PATH environment variable is important - if the path for your ruby 1.9.3 executable appears before the path for your ruby 2.0.0 executable, then the interpreter will use the 1.9.3. So, for example;

*

*Ruby 1.9.3 is in /c/Software/Ruby/1.9.3/ruby.exe

*Ruby 2.0.0 is in /c/Program Files/Ruby/2.0.0/ruby.exe

And your PATH variable is as follows;
$ echo $PATH
/c/GIT/bin:.:/c/Software/Ruby/1.9.3/:/c/Program Files/Ruby/2.0.0/

Then you would need to re-order your PATH variable so that the 2.0.0 path comes before the 1.9.3 path. Find your .bashrc file (by default in your home directory) and examine any PATH definitions, e.g.;
PATH=$PATH:/c/Program Files/Ruby/2.0.0/

And modify so that your 2.0.0 path has precedence
PATH=/c/Program Files/Ruby/2.0.0/:$PATH

You can issue this command on the command line also, making sure to do
$ export $PATH

once you've made your changes. Otherwise you'll need to source .bashrc or start a new shell. GIT Bash should then pick up the correct executable.
An alternative is to create aliases or symbolic links for each executable which specifies their version, such that typing ;
$ ruby193

Executes the 1.9.3 ruby and
$ ruby200

executes the 2.0.0 version.
Aliasing is as follows;
$ alias ruby193=/c/Software/Ruby/1.9.3/ruby.exe

Linking is as follows;
$ ln -s /c/Software/Ruby/1.9.3/ruby.exe /c/GIT/bin/ruby193

Aliases you use frequently should be put in .bashrc .


text:
Q: Download DocumentSet as zip using csom How do I download a documentset as zipped file using SharePoint client object model.

A: Please check the following links:
Download Document Set as zip
Create a SharePoint Custom Action to Zip and Download a Document Set


text:
Q: How can the augmented system model be not stabilizable when the original system model is? I have a nonlinear system with m=4 states and n=1 input which represents the propulsion system of a vehicle (regulates the speed by controlling the engine torque). I wish to apply an LQR controller with integral action (LQI) to the linearized model of the plant, however I am having problems with the stabilizability of the resulting augmented model. A linearized model around a steady state is the following:
$System 1:$
$$A=\begin{pmatrix}
-0.0024 & 0.0003 & 0 \\
0 & -0.3531 & 0.5308 \\
0 & 0 & -0.33
\end{pmatrix},   B=\begin{pmatrix}
 0 \\
 0 \\
0.33
\end{pmatrix}$$
$$ C = I, D=0$$
The input (commanded torque) affects solely state $x_3$ (generated torque), which in turn affects state $x_2$ (engine speed), which itself finally affects state $x_1$ (vehicle speed) through $A_{12}$.
In the footsteps of this question, before applying LQI one needs to first verify that the augmented system
$System 2:$
$$Aa=\begin{pmatrix}
A & 0_{mxn} \\
-C & 0_{n x n} \\
\end{pmatrix},   Ba=\begin{pmatrix}
 B \\
 -D \\
\end{pmatrix},   Ca=\begin{pmatrix}
 C \\
 0_{m x m} \\
\end{pmatrix}$$
is stabilizable, which corresponds to checking if any uncontrollable modes which are also unstable, exist. Following the answer of user SampleTime in the aforementioned question, it is shown that $System2$ is indeed not stabilizable, since the corresponding $A_{a,uc}$ is not a Hurwitz matrix. The matlab 'lqi' command itself throws an error, presumably for this reason.
What is the mathematical interpretation of this? My intuition is that the control system does not have sufficient control authority over state $x_1$ (notice that $A_{12}$ is 10 times smaller than the negative "dissipation" term $A_{11}$. How does one go about fixing this?
Matlab code below:
A = [-0.00244,0.0003,0;
    0,-0.3531,0.5307;
    0,0,-0.3333];
B = [0;0;0.33333];
C = eye(3);
D = 0;
sys1 = ss(A,B,C,D);

% Augment system1
[ny, nu] = size(sys1.D);
nx = size(sys1.A,1);
Aa = [sys1.A zeros(nx,ny); -sys1.C zeros(ny,ny)];
Ba = [sys1.B ; -sys1.D];
Ca = [sys1.C, zeros(nx, nx)];
sys2 = ss(Aa, Ba, Ca, D);

[Aa_bar, Ba_bar, Ca_bar, T, k] = ctrbf(Aa, Ba, Ca);
n_uc = size(Aa, 1) - sum(k); % Number of uncontrollable modes
Aa_uc = Aa_bar(1:n_uc, 1:n_uc);

disp(Aa_uc)

A: The issue here is that you have three semisimple eigenvalues located at 0 and so  you will need to have at least 3 control input to stabilize those modes. As an example, just consider a 3-dimensional system $$\dot{x} = Bu$$ and try to see how many control inputs you need to stabilize this system.
For current problem, the pair $(A,B)$ is trivially stabilizable since $A$ is Hurwitz stable. So, in the end, you just need to stabilize the 3 semisimple zero eigenvalues. Let $u=\epsilon(K_1x+K_2z)$ where $z$ is the second state of the augmented system and $\epsilon>0$ is a small parameter.
The (normalized) left- and right-eigenvectors associated with the zero-eigenvalue of $A_a$ are given by
$$U=\begin{bmatrix}CA^{-1} & I\end{bmatrix}\ \mathrm{and}\ V=\begin{bmatrix}0\\I\end{bmatrix}.$$
Using perturbation theory, we can study the behavior of the eigenvalues of
$$A_a(\epsilon):=\begin{bmatrix}A+\epsilon BK_1 & \epsilon BK_2\\-C & 0\end{bmatrix}$$
for small enough $\epsilon$'s. It turns out that the zero eigenvalues of $A_a(0)$ bifurcate under the action of $\epsilon$ following the eignvalues of
$$\epsilon CA^{-1}BK_2$$ for small enough $\epsilon$'s whereas the other eigenvalues remain stable. So, the system is stable for any sufficiently small $\epsilon$ (in absolute value) provided that either  $CA^{-1}BK_2$ is Hurwitz stable (all the eigenvalues have negative real part) or it is anti-Hurwitz stable (all the eigenvalues have positive real part).
Since $C=I$, $A$ is nonsingular, then the only way this could be made possible is that $BK_2$ be of rank $m=3$. So, we need at least 3 control inputs.


text:
Q: How to directly call admin in django urls In my python I have urls like :
urlpatterns = [
    path('admin/', admin_site.urls),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

when i have url like : http://localhost:8000/ i am getting screen like

but when i am using  http://localhost:8000/admin i am able to use my admin login pannel.what i actually want is when i use http://localhost:8000/ it directly call the http://localhost:8000/admin .can anyone please help me related this ??

A: Just remove the word admin from your url, like this:
path('', admin_site.urls),

This means that your admin page will be your home page.
Alternatively, you could do a redirect:
from django.views.generic.base import RedirectView
from django.urls import re_path
re_path(r'^$', RedirectView.as_view(url='/admin'))


text:
Q: how to print everything from a dictionary? I'm trying to do this question for class that is really confusing me, I can't seem to figure it out. They give me this code and say that I need to do something to make it print all of the flowers in the dictionary instead of printing just one. Here is the code that is provided, which just prints one of the flowers.
def build_floralArrangement(size, **flowers):  # **flowers is a list of key-value pairs to add to the dictionary.

    """Build a dictionary containing customer requests for flowers."""

    arrangement = {}

    arrangement['size'] = size

    for key, value in flowers.items():

        arrangement[key] = value

        return arrangement

myArrangement = build_floralArrangement('large', flower1 = 'tulips', flower2='red roses', flower3='white carnations')

print(myArrangement)

A: This should work:
def build_floralArrangement(size, **flowers):  # **flowers is a list of key-value pairs to add to the dictionary.

    """Build a dictionary containing customer requests for flowers."""

    arrangement = {}

    arrangement['size'] = size

    for key, value in flowers.items():

        arrangement[key] = value

    return arrangement

myArrangement = build_floralArrangement('large', flower1 = 'tulips', flower2='red roses', flower3='white carnations')

print(myArrangement)

Output:
{'size': 'large', 'flower1': 'tulips', 'flower2': 'red roses', 'flower3': 'white carnations'}

All I did was move your return statement out of your for loop.

A: unindent return arrangement
because this way you are returning a single key-value object:
for key, value in flowers.items():

    arrangement[key] = value

return arrangement

If you want to show only the flowers I would do the following (as advice):
myArrangement = build_floralArrangement('large', flower = 'tulips', flower='red roses', flower='white carnations')

and then:
for key, value in flowers.items():

    arrangement[key] += value

return arrangement

And then to show the flowers:
print(arrangement.get('flowers'))

In this way you have a simpler dictionary and that can be used for more things, I hope it helps you


text:
Q: Valid AM-GM inequality proof? We have to prove that $$\frac{(x_1+x_2+x_3+...+x_n)}{n} \geq (x_1\cdot x_2\cdot x_3\cdots x_n)^{1/n}$$
Attempt: Raising both sides to the nth power gives $\left(\frac{x_1+x_2+x_3+...x_n}{n}\right)^{n} \geq x_1x_2x_3...x_n$
This is equivalent to proving that if a sum of random numbers is a fixed number, then their maximum product occurs when all the number are equal. So we have to find which combination of numbers gives the maximum product if their sum is fixed.
Obviously $$\left({x_1+x_2+x_3+...x_n}\right)^{n} > x_1x_2x_3...x_n$$
then, a maximizer must exist.
Now suppose that we have this combination of products: $x_1x_2x_3...x_n$
If i take the arithmetic mean of any 2 numbers and replace them by their arithmetic mean, I will get a bigger product (By the simple 2 case AM-GM inequality which is easy to proof), obviously the arthimetic mean of 2 numbers will not change the sum of the numbers, we can write that:
$$\frac{x_1+x_2}{2}\cdot\frac{x_1+x_2}{2}\cdot x_3 \cdots x_n\ \geq x_1x_2x_3\cdots x_n$$
Which means if we have any combination of product of numbers, I could increase that product by making any 2 numbers equal (arthimetic mean) without changing the sum of the numbers.
Now supposing that the maximum product does not have all of the numbers equal, then I can increase its product by having 2 numbers equal, so this mean that it's not the maximum product, then, by contradiction, the maximum product must occur when all the numbers are equal (Sum divided by the number of numbers)
Which means that $$\left(\frac{x_1+x_2+x_3+...x_n}{n}\right)^{n} \geq x_1x_2x_3...x_n$$
Is this a valid proof? It's my first time here and I don't know how to do the math notations thingy on this website so forgive me, thanks.

A: That's pretty good.
One aspect I'd want to fiddle with is the existence of the maximizer.  You argued that it's bounded (which as a commenter noted could be made more explicit) and so a maximizer exists; this requires some kind of compactness argument, and the continuity of $\mathbb R^n\to\mathbb R$, $(x_1,\dotsc,x_n)\to\prod_{k=1}^n x_k$.  That's all fine, but it would be better to make it explicit.
If you don't want to use topological concepts like that, then the argument can be adjusted not to assume the existence of the maximizer, but to prove it.  The idea is to repeatedly replace pairs of $x_i$ until they're all the same, and argue (as you did) that we can do this keeping the AM constant but increasing the GM.  The only tricky bit is that, if you replace pairs of numbers with their average, this process might not ever stop.  (Example: $(1,2,2)\to (\frac32,\frac32,2)\to (\frac32,\frac74,\frac74) \to\dotsm$.)  So the replacement step has to be tweaked.  The resulting proof can be found in a note by Dijkstra, EWD1140.

A: Hint: Your idea is correct. Here is a north to let things rigorous.
Consider $f, \psi : U \to \mathbb R$ defined as $$ f(x) = x_1 \cdot x_2  \cdots x_n \,\,\, \text{and} \,\,\, \psi (x) = x_1 + x_2 + \ldots + x_n$$
for all $x = (x_1, x_2, \ldots , x_n) \in U$. Fix $s > 0$ and search for the critical points of $f|_M$ where $M = \psi^{-1}(s)$.
Observe that $\mathrm{grad} \, \psi (x) = (1,1,\ldots, 1)$ for any $x \in U$ and $\mathrm {grad}\, f (x) = (\alpha_1 , \ldots , \alpha_n)$, with $a_i = \prod_{j\neq i} x_j$. Show that the maximum is necessarily in $M$ and is the only critical point of $f|_M$.


text:
Q: Require cycle issue when using BotFramework DirectLine JS with axios I'm trying to work with Microsoft Bot Framework in react native using DirectLine API. Everything works properly but as soon as I initiate axios GET call I get error

Require cycle: node_modules/core-js/internals/microtask.js ->
node_modules/core-js/internals/microtask.js
Require cycles are allowed, but can result in uninitialized values.
Consider refactoring to remove the need for a cycle.

It only happens when I intialize DirectLine API, if I comment out and remove the DirectLine API, the axios works fine. Both are different APIs, I'm unable to figure out why using DirectLine API is causing the axios to stop working.
Here is the code
import React,{useEffect} from 'react';
import {
  SafeAreaView,
  View,
  TouchableOpacity,
} from 'react-native';

import { DirectLine } from "botframework-directlinejs";

var directLine

const App = () => {

  useEffect(()=>{
    directLine = new DirectLine({
        secret: "XXXXX"
    });
    directLine?.activity$.subscribe(botMessage => {
      alert("BotMessage")
    });
  },[])

  const onSend = () => {
  let msgPayload = {
    from: { id: 'abc', name:'human'},
    type: 'message',
     text: "Hello"
  }
      directLine.postActivity(msgPayload).subscribe(() => console.log("success"), () => console.log("failed"));
  };

  const onApiSend = () => {
  const axios = require('axios').default;
  axios.get('https://api.github.com/users/mapbox')
  .then((response) => {
    alert("Api Called Success")
  });
  }

onApiSend only works if I remove the useEffect (DirectLine JS) part. Otherwise I get error related to Require cycle

A: The issue is in the BotFramework DirectLine JS library and in order to make it work in react native, the library needs to be rebuild (both lib and dist) folder with minor change. The github repo should be forked and the line in BotFramework-DirecLineJS/src/directLine.ts should be changed from
import 'core-js/features/promise';

to
import 'core-js/modules/es.promise.finally';


text:
Q: backtracking to match html tag using PHP I am trying to figure out how to use Regex in PHP to backtrack and find a
 tag preceding some specific html.
Here is the full HTML I want to look at including the closing tag I want to find and ultimately remove from the string:

Grades

It actually has a new line and spaces in between the 2 tags.  So I want to target that
 tag and remove it from the string.  Any help would be appreciated.
I am using an online regex tester.  Here is what I have right now.
Regex:
/(
)([\w\W]*?)(<div)/

A: I suspect if this question is about parsing HTML document at all and regex is totally fine to deal with it:
preg_replace('~
\s+(?=<div)~', '', $content);

will do the job. You needed a positive lookahead and considering whitespaces in middle of closing and opening tags, precisely.


text:
Q: 'Newtonsoft.Json.Linq.JArray' to 'System.Web.UI.WebControls.ListItemCollection' I have a Json file as shown below. I want to convert only the  option node in the JSON file into a C# ListItemCollection object
ASP.net File:
   var path = Server.MapPath(@"~/json.json");
    using (StreamReader r = new StreamReader(path,false))
    {
        string json = r.ReadToEnd();
        dynamic arr = JsonConvert.DeserializeObject(json);
        ListItemCollection licRB = new ListItemCollection();
        licRB = arr.AnswerRadioButton.option;<<-- run time error is produced here
    }

JSON File:
{   "FormTitle": "This is Form Title from JSON",
  "TitleQuestion1": "This is the Title of Question 1",
  "TextQuestion1": "1- This is the text of Quextion Number 1",
  "AnswerRadioButton": {
"visible": "true",
"title": "Radio Button Title",
"FieldsetRBStyle": { "border": "1px" },
"option" : [
  {
    "text": "text1",
    "value": "v1",
    "checked": "false"
  },
  {
    "text": "text2",
    "value": "v2",
    "checked": "true"
  },
  {
    "text": "text3",
    "value": "v3",
    "checked": "false"
  },
  {
    "text": "text4",
    "value": "v4",
    "checked": "true"
  }
]  }}

A: Assuming that you have the required classes (e.g. using this tool) you can access the options like this:
var test = JsonConvert.DeserializeObject<RootObject>(json);
var options = test.AnswerRadioButton.option;


text:
Q: Dúvida usando o FireDac com TClienteDatSet Estou usando estes componentes mais estou tendo o seguinte erro ao tentar abri o ClientDataSet.
Gera o erro:

Access violation at address 50FCDC6F in module 'dsnap230.bpl'. Read of
  address 00000000.
TDFConnection para conexão ao banco
TDFQuery com a consulta sql de uma tabela para teste
TDataSetProvider com a propriedade DataSet ligado ao TDFQuery,
  ativando as propriedades poAllowCommandText é poPropogateChanges
TClienteDatSet ligado ao TDataSetProvider na propriedade ProviderName

A: adicione  'MidasLib' ao uses  aonde vc tiver seu ClientDataset para fazer a conexão remota com o dataSetProvider.

A: Tente usar o componente FDMemTable no lugar do ClientDataSet e no lugar de usar o DataSetProvider use o .Data da FDQuery e .Data do MemTable para passar o conteúdo. Depois que comecei a fazer isso não tive mais dor de cabeça com ClientDataSet. Exemplo:
  if (FDQuery.Active) then
    FDQuery.Close;
  FDQuery.SQL.Clear;
  FDQuery.SQL.Add('SELECT CAMPO FROM TABELA');
  FDQuery.Open;
  FDMemTable.Data := FDQuery.Data;


text:
Q: Accessing raster values to create histogram using ArcPy? Using native Python and arcpy function what method is best to create a histogram of raster dataset? I know it's possible to use raterio and GDAL functions, but I would like to keep it a arcpy and native Python.
Specifically I am working on a script to delineate watersheds and I would like to create a raster based on the values in a flow accumulation raster dataset. From the calculated raster I would then convert to vector stream layers. The ultimate goal is to be able to create separate stream order layers.

A: I would recommend converting your raster to a numpy array, which you can then use to calculate statistics for the histogram. matplotlib is then used for the plotting. For example:
import arcpy
import numpy as np
import matplotlib.pyplot as plt

# This example uses an 8bit unsigned format TIFF image
tiff = r'C:\path\to\your\image.tif'

# Convert raster to numpy array and calculate histogram
array = arcpy.RasterToNumPyArray(tiff)
hist, bins = np.histogram(array, bins = [25,50,75,100,125,150,175,200,225,250,275])

# Plot the histogram
plt.bar(bins[:-1], hist, width = 25)
plt.xlim(min(bins), max(bins))
plt.ylabel('Pixel Count')
plt.xlabel('Pixel Values')
plt.show()

However, I believe Rasterio does a better job plotting raster histograms. For example, here is a Rasterio generated histogram of 4 band NAIP imagery:
import rasterio
from rasterio.plot import show_hist

src = rasterio.open("path/to/your/image.tif")
show_hist(
    src, bins=50, lw=0.0, stacked=False, alpha=0.3,
    histtype='stepfilled', title="Histogram")


text: Q: How does the wavefront of sound or any other type of longitudinal waves look like? In reality there is no crest on a longitudinal wave, even though compression is basically crest. So on this basis, there is really no visible wavefront. Is this true?


text:
Q: Blank rows is skipped while reading data from the excel sheet i try to read the data from excel and store in vector list. But i'm having two issue when applied the following code in my system, hope can get some guidance.

1) When i run the system it will read all the data from the excel file but it skipped those blank data. How can i make it as empty string rather than skipped. Result : from this Excel file you can see that between value 145 and 2DHatchback is blank data, but system will skipped it, how can i make it as empty string " "?.
[PAS, 04/01/2015, ALFA ROMEO, 145, 2D HATCHBACK, 5 SP MANUAL, 1598.42, GZ095G, 02, 01, 02, MULTI POINT F/INJ, ITALY, 9400, 7800]
2) When i tried to deleted few rows of data in excel, my vector result still will keep the deleted data but remain as empty.
Result: from this Excel file if i manually delete row 11 and row 12, when i system.out.println the vector result it will show as [, , ] , [, , ] for deleted rows.
Readexcel.java
public Vector getexcel(String filename)
    {
        String filetype =  filename.substring(filename.lastIndexOf(".")+1);
        Vector cellVectorHolder = new Vector();

        try
        {
            Workbook workBook = WorkbookFactory.create(new FileInputStream(filename));
            Sheet sheet = workBook.getSheetAt(0);
            Iterator rowIter = sheet.rowIterator();
             if(filetype.equals("xlsx"))
            {
                while(rowIter.hasNext())
                {
                    XSSFRow row = (XSSFRow) rowIter.next();
                    Iterator cellIter = row.cellIterator();
                    Vector cellStoreVector=new Vector();

                 if(row.getRowNum()>1)
                    {
                        while(cellIter.hasNext())
                        {
                            XSSFCell cell = (XSSFCell) cellIter.next();
                         Integer cellType = cell.getCellType();
                         String cellTypeDesc    = "";
                         String cellValue       = "";

                              switch (cellType)
                              {
                              case 0:
                                  cellTypeDesc = "NUMERIC";
                                  String doubleValue = cell.getRawValue();

                                  if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                      if (HSSFDateUtil.isValidExcelDate(Double.parseDouble(doubleValue))) {
                                          Date date = HSSFDateUtil.getJavaDate(Double.parseDouble(doubleValue));

                                          DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                                          cellValue = df.format(date);
                                      }
                                  } else {

                                      cellValue = String.valueOf(doubleValue);
                                  }
                                  break;
                              case 1:
                                  cellTypeDesc = "STRING";
                                  cellValue = cell.getStringCellValue();

                                  break;
                              case 3:
                                  cellTypeDesc = "BLANK";
                                  cellValue = "";
                                  break;
                              }

                            cellStoreVector.addElement(cellValue);
                        }
                    }
                    cellVectorHolder.addElement(cellStoreVector);
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        return cellVectorHolder;
    }

A: Excel stores empty fields, so you need to do manual checking
You should check for rows containing only empty cells. Just write a check before you add it to the cellStoreVector
Also, if the rowNumber increases by more than 1, you could add empty row-vectors yourself. So store the previous rowNumber and compare to the current rowNumber


text:
Q: component-wise multiplication for 3d vectors in windows store app programming How to do component-wise multiplication of two 3d vector? it seems MS didn't provide such functions in DirectXMath.h, what's Microsoft doing there? in the old SDKs(DX 10/9), I can make a product of two vectors directly as:
v3 = v1 * v2;
or multiply a vector by a scalar like:
v2 = v1 * 1.0f;
but now, there is no operator * for XMVECTOR type, so I can't do that. so I need to make the product manually as
v3 = (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z);
although it is not so difficult, I think DirectXMath should provide such a basic function.

A: The dot product can be achieved with XMVector*Dot method. MSDN link for dot3product.
And the good page exists on msdn with methods list: MSDN
Also, I think that Microsoft didn't make operator* override because it is not clear which product this operator should use - dot or cross product.


text:
Q: Can't access Node.js server on web server I'm trying to test a simple Node.js server on my webserver. The problem is that I can't access the Node.js server from my chrome browser and I have searched without any success.
This is my basic server.js script (server side)
var app = require('express')();

app.get('/test', function (req, res) {
    console.log('web page opened');
});

app.listen(3000, function () {
    console.log('Listening on port 3000');
});

When I run the node in console I get result as expected
public_html$ node server.js
Listening on port 3000

Now when I try to access the URL like this:
http://xxx.xxx.xxx.xxx:3000/test the connection times out and I do not get anything.
This prevents me from using $.ajax form to send data to my node server and the jquery request fails with error as connection timed out issue as well because the URL:3000 with my nodejs port is not accessible.
It seems like my host (Cloudways) does not allow access on any port. If that is case, what can I do really in this situation?
Note: I do not have root access to the server, they can't give root access for security.

A: Actually going thru Apache to access your app server, nodeJs in your case, is the standard way to avoid security vulnerabilities etc.. You can configure your Apache server as follows:
<VirtualHost *:80>
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName www.example.com
  ServerAlias example.com
  ProxyPass / http://localhost:3000/test/
  ProxyPassReverse / http://localhost:3000/test/
</VirtualHost>

The you would call your app at http://xxx.xxx.xxx.xxx:80/test or simply at http://xxx.xxx.xxx.xxx/test  since 80 is implied for HTTP and apache will call http://xxx.xxx.xxx.xxx:3000/test for you.
EDITED: This should work thru .htacccess too - which is what, it seems cloudways wants you to do : https://support.cloudways.com/what-can-i-do-with-an-htaccess-file/

A: Best way to test node.js is to use node process manager on your server like https://www.npmjs.com/package/pm2.
This will save a lot of time for deployment. but you will need root access to install this package. if you does not have root access then ask your hosting provider to DO install these packages for you.
If in any case you did not get root access and you have no access to open port and install packages for your project. Then use any other hosting like https://www.linode.com/.


text:
Q: Select and count rows in the same query? I am trying to find a way to select and count some rows in my database. I was checking the MySQL docs and this is what I came up with:
$query = "SELECT *, COUNT(*) as total WHERE IMAGE != '' AND CATEGORY = '$category' $limit";

But this outputs a single row when done... :(
Than I have tried:
$query = "SELECT * FROM PRODUCTS,
        (SELECT COUNT(*) as total FROM PRODUCTS WHERE IMAGE != '' AND CATEGORY = '$category') as x
        WHERE IMAGE != '' AND CATEGORY = '$category' $limit";

This works, however I don't really know if this will perform well, because of the two SELECT statements (lus I don't need 'as x', but without this the query fails).
Is there a better way?
Thanks

A: Another way is using sub-query but not sure about the performance should be executed only once since there is no correlation from outer table
SELECT *, (select COUNT(*) from PRODUCTS) as total
WHERE IMAGE != ''
AND CATEGORY = '$category' $limit


text:
Q: $\gamma_k^m = (E,p,G_k(F^m))$ is locally trivial I'm currently studying bundles from Husemaller and I'm stuck with the proof that $\gamma_k^m = (E,p,G_k(F^m))$ at p.$25$.
The thing I don't get is why $U_H$ is open and $h_H$ is an isomorphism. It should be obvious since not many words have been spoken but I don't see clearly the reason since the topology on $G_k(F^m)$ is a little hard to visualize.
Trying to incorporate Hatcher notes p.$28$ Lemma $1.15$ it seeems that Hatcher defines $U_l$ which seems to have a different definition from the one given by Husemaller. Are the two definition the same?
Any help to disambiguate the problem or any solution would be appreciated.

A: The openess of these sets is not obvious. But you can try to get more intuition by looking at the examples $G_1(\mathbb{R}^2)=\mathbb{RP}^1,\; G_2(\mathbb{R}^3) = \mathbb{RP}^2$, where you can draw a bit. Just visualize a point in $G_1(\mathbb{R}^2)$ as a line in $\mathbb{R}^2$ and now try to guess how an open neighbourhoud of this point looks like. The open sets given by Husemoller are generalisations of the "standard" trivialsiations for projective spaces.
Husemoller defines for each $H \subset \{ 1,\ldots ,m\} $ with $\#H = k$ a $k$ dimensional subspace of $F^m$ which can be written as $\{(x_1,\ldots,x_m) \in F^m \; |\; x_i = 0 \text{ for } i \notin H\}$. In the book its defined by the image of a monomorphism $u_H:F^k \to F^m$. Note that $u_H(F^k) \in G_k(F^m)$.
Also $\pi: G_k(F^m)\times F^m \to F^m$ is defined, such that $\pi(V,x)$ is the orthogonal (there seems to be a scalar product) projection of $x$ into $V$. So for $V \in G_k(F^m)$ we have a map (compare to Hatcher notes) $\pi(V, -) = \pi_V: F^m \to V$. Now the subset $U_H$ in Husemoller is defined to be (there is a typo in the definition in the book)
$$U_H := \left\{V \in G_k(F^m) \; |\; \pi_V\circ u_H:F^k \to V \text{ is bijective } \right\}.$$
In Husemoller's notation, Hatcher defines for each $W \in G_k(F^m)$ the set
$$ U_W := \left \{ V \in G_k(F^m)\; | \; \pi_W(V) \subset W \text{ has dimension }  k\right\}.$$
Since $W$ has dimension $k$, that is saying $\pi_W|_V : V \to W$ is bijective. So you see that $U_H = U_W$, if we take $W = u_H(F^k)$. So Hatcher is describing open neighbourhoods for any point in $G_k(F^m)$ while Husemoller is only doing it for the $\binom{m}{k}$ "standard" points. Now you can use Hatcher's proof for openess. The moral is, that if you have $V \in U_W$ and you "change $V$ a little" the dimension of $\pi_W(V)$ will not change. This can be very nicely drawn for $G_1(\mathbb{R}^2)$.
From these descriptions it shoud be clear that $$h_H: U_H \times F^k \to p^{-1}(U)\\ (V, x) \mapsto (V,\pi(V,u_H(x)))$$ is bijective and a linear isomorphism on the fibres. The proof for continuity is given in Hatcher's notes.


text:
Q: What to do to make the app "qualified on iOS 4"? I have not had much time to read through all the documentation for the 1500 more features included in iOS4, so right now I have 2 questions:

*

*If the app is just a usual utility application, what to do to make it "qualified on iOS 4"?

*If the app uses a timer to refresh all the items on the screen every one minute (requires redrawing of the sub views), what are the changes that have to be done? ( I notice that even though when I quit the application, open it again in a 3GS iPhone, the timer is still generating events).

Update
What I want is the technical part of the story, not the description on the appstore, etc...
E.s. Those applications above have to do something with applicationWillResignActive, applicationDidEnterBackground, applicationWillEnterForeground, applicationDidBecomeActive, etc...

A: This is something that Apple do when testing your app after you submit it via iTunes Connect.
They will test your app on iOS4 and if they decide it works sufficiently, they'll mark it as tested on iOS4.
If, for whatever reason, it doesn't work well on iOS4, they'll reject the app and let you know what was wrong.

A: It's a label given automatically by Apple after they test it on iOS4. You may not actually need to do anything extra to get it.


text:
Q: SpreadsheetApp / FormApp - Changelog I have a script that records a log of all changes in a spreadsheet:
function onEdit() {

  var timestamp = new Date();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var cell = sheet.getActiveCell();
  var user = Session.getActiveUser();
  var columnLabel = sheet.getRange(1, cell.getColumn()).getValue();
  var changelogSheet = ss.getSheetByName("Changelog");

  changelogSheet.appendRow([timestamp, cell.getA1Notation(), columnLabel, cell.getValue(), user.getEmail()]);
}

This codes beautifully creates a row of data in "Changelog" sheet every time there is an edit on "Sheet1". It tells you the date and time, the cell where it was edited, the contents of edit and user who edited it.
My issue is that "Sheet1" is linked to a Google Form that allows users to edit their responses. When users indeed edit their responses on Google Forms, the edit is not registered on my script and there is no log for it.
I presume my script only logs physical edits on the sheet itself.
Is there a way (perhaps using FormApp) to do a similar code that logs every edit on a Google Form?
I really appreciate your help.

A: You should create a new onFormSubmit trigger that will include similar logic and create a new row in the Google Sheet when a form response is submitted.


text:
Q: How to pick just one item from a generator? I have a generator function like the following:
def myfunct():
  ...
  yield result

The usual way to call this function would be:
for r in myfunct():
  dostuff(r)

My question, is there a way to get just one element from the generator whenever I like?
For example, I'd like to do something like:
while True:
  ...
  if something:
      my_element = pick_just_one_element(myfunct())
      dostuff(my_element)
  ...

A: You can pick specific items using destructuring, e.g.:
>>> first, *middle, last = range(10)
>>> first
0
>>> middle
[1, 2, 3, 4, 5, 6, 7, 8]
>>> last
9

Note that this is going to consume your generator, so while highly readable, it is less efficient than something like next(), and ruinous on infinite generators:
>>> first, *rest = itertools.count()

A: Create a generator using
g = myfunct()

Everytime you would like an item, use
next(g)

(or g.next() in Python 2.5 or below).
If the generator exits, it will raise StopIteration.  You can either catch this exception if necessary, or use the default argument to next():
next(g, default_value)

A: For picking just one element of a generator use break in a for statement, or list(itertools.islice(gen, 1))
According to your example (literally) you can do something like:
while True:
  ...
  if something:
      for my_element in myfunct():
          dostuff(my_element)
          break
      else:
          do_generator_empty()

If you want "get just one element from the [once generated] generator whenever I like"  (I suppose 50% thats the original intention, and the most common intention)  then:
gen = myfunct()
while True:
  ...
  if something:
      for my_element in gen:
          dostuff(my_element)
          break
      else:
          do_generator_empty()

This way explicit use of generator.next() can be avoided, and end-of-input handling doesn't require (cryptic) StopIteration exception handling or extra default value comparisons.
The else: of for statement section is only needed if you want do something special in case of end-of-generator.
Note on next() / .next():
In Python3 the .next() method was renamed to .__next__() for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function next() did not exist. And it was even discussed to move next() to the operator module (which would have been wise), because of its rare need and questionable inflation of builtin names.
Using next() without default is still very low-level practice - throwing the cryptic StopIteration like a bolt out of the blue in normal application code openly. And using next() with default sentinel - which best should be the only option for a next() directly in builtins - is limited and often gives reason to odd non-pythonic logic/readablity.
Bottom line: Using next() should be very rare - like using functions of operator module. Using for x in iterator , islice, list(iterator) and other functions accepting an iterator seamlessly is the natural way of using iterators on application level - and quite always possible. next() is low-level, an extra concept, unobvious - as the question of this thread shows. While e.g. using break in for is conventional.

A: I don't believe there's a convenient way to retrieve an arbitrary value from a generator.  The generator will provide a next() method to traverse itself, but the full sequence is not produced immediately to save memory.  That's the functional difference between a generator and a list.

A: Generator is a function that produces an iterator. Therefore, once you have iterator instance, use next() to fetch the next item from the iterator.
As an example, use next() function to fetch the first item, and later use for in to process remaining items:
# create new instance of iterator by calling a generator function
items = generator_function()

# fetch and print first item
first = next(items)
print('first item:', first)

# process remaining items:
for item in items:
    print('next item:', item)

A: generator = myfunct()
while True:
   my_element = generator.next()

make sure to catch the exception thrown after the last element is taken

A: For those of you scanning through these answers for a complete working example for Python3... well here ya go:
def numgen():
    x = 1000
    while True:
        x += 1
        yield x

nums = numgen() # because it must be the _same_ generator

for n in range(3):
    numnext = next(nums)
    print(numnext)

This outputs:
1001
1002
1003

A: I believe the only way is to get a list from the iterator then get the element you want from that list.
l = list(myfunct())
l[4]


text:
Q: Changing SSH passwords doesn't do anything I recently set up ssh on my linux mint server. I wanted to change the password on it because of security reasons. I followed this guide to change the password. The password was successfully changed, and I know because if I want to change it again the 'old password' is the one I changed it to. However, when I try to login, the new password is denied, and the old password is accepted. Any help appreciated!

A: There are two authentication methods at play here: password-based and key-based.
The guide you have linked to provides instructions to change the passphrase, which only affects key-based auth. As noted in the guide, a passphrase is used to add another layer of protection to an SSH private key. When you change a passphrase, the change occurs on the client side.
If the server does password-based auth, you would see no difference. Passwords are authenticated on the server side, against a user directory of some kind. This can be the default /etc/shadow file, or something more complex such as an LDAP server.
ssh -vvv will help diagnose this. The debugging output will show the list of authentication methods that the server accepts, and which one is currently being used.


text:
Q: C# WinForms — Как правильно парсить json? Пишу программу с VK Api, делал GET запрос, далее возникли проблемы с парсингом json. Когда запускаю программу ничего не отображается... Вот код:
public class Account
    {
        public string id { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string bdate { get; set; }
    }

private void Example_Load(object sender, EventArgs e)
    {
        var client = new WebClient();
        using (var stream = client.OpenRead("https://api.vk.com/method/users.get?user_ids=210700286&fields=bdate&v=5.64"))
        using (var sr = new StreamReader(stream))
        {
            var text = sr.ReadToEnd();

            Account m = JsonConvert.DeserializeObject<Account>(text);

            textBox1.Text = m.id;
            textBox1.Text += " ";
            textBox1.Text += m.first_name;
            textBox1.Text += " ";
            textBox1.Text += m.last_name;
            textBox1.Text += " ";
            textBox1.Text += m.bdate;
        }
    }

В чём проблема? За ранее огромное спасибо

A: Ваш запрос возвращает следующий JSON:
{"response":[{"id":210700286,"first_name":"Lindsey","last_name":"Stirling","bdate":"21.9.1986"}]}

Он не совпадает с вашим классом Account.
Если скопировать его в буфер обмена и выполнить в Visual Studio команду меню Edit > Paste Special > Paste JSON As Classes, то будут сгенерированы следующие классы:
public class Rootobject
{
    public Response[] response { get; set; }
}

public class Response
{
    public int id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string bdate { get; set; }
}

Становится понятно, что возвращается объект, содержащий массив данных о пользователях.
Следующий код должен работать:
var root = JsonConvert.DeserializeObject<Rootobject>(text);

foreach (var response in root.response)
    Console.WriteLine(response.id + " " + response.first_name +
        " " + response.last_name + " " + response.bdate);

Желательно названия классов и свойств привести к общепринятым в C# стандартам и сделать их более осмысленными:
[JsonObject("Rootobject")]
public class Response
{
    [JsonProperty("response")]
    public Account[] Accounts { get; set; }
}

[JsonObject("Response")]
public class Account
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("first_name")]
    public string FirstName { get; set; }
    [JsonProperty("last_name")]
    public string LastName { get; set; }
    [JsonProperty("bdate")]
    public string BirthDate { get; set; }
}

var response = JsonConvert.DeserializeObject<Response>(text);

foreach (var account in response.Accounts)
    Console.WriteLine(account.Id + " " + account.FirstName +
        " " + account.LastName + " " + account.BirthDate);


text:
Q: C# reading console output of a 3rd party tool with a correct code page We have to execute a 3rd party sw which is a console tool and writes some text to the output. We sepcify the output encoding before the execution as follow:
 var proc = new Process {
  StartInfo = new ProcessStartInfo {
    FileName = exeName,
    Arguments = cmdLineArgs,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    RedirectStandardInput = true,
    CreateNoWindow = true,
    StandardErrorEncoding = Encoding.UTF8,
    StandardOutputEncoding = Encoding.UTF8,
 },
 EnableRaisingEvents = true,
};

We read the output as:
var stdOut = new StringBuilder();
proc.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e)
  => stdOut.Append(e.Data + "\r\n");
proc.BeginOutputReadLine();

We constructed a simple console tool to test it:
System.Console.OutputEncoding = System.Text.Encoding.UTF8;
System.Console.WriteLine("2 На берегу пустынных волн Τη γλώσσα μου έδωσαν ελληνική Pòsso mangiâ o veddro e o no me fà mâ.");

The strange that even if we set the output encoding or not - we cannot read the output back (we found somee ?? ???? ???? string instead).
The real issue is to read a 3rd party tool output in a correct way. We dont know if the tool sets the output encoding or not. When not - what is the encoding it uses. But until we cannot read our own tool output correctly - there is no chance to read the 3rd party as well. What do we miss now? Any advice is welcome!


text:
Q: ggplot2: User defined continuous scale I would like to make a density plot with a user-defined x-axis:
library(ggplot2)

ggplot(dataset, aes(x = VarX, fill = varFill)) +
scale_x_continuous(breaks = seq(0, 1000, by = 100)) +
geom_density(alpha= .5, aes(coulour = varFill)) +
xlim(c(0, 1000))

However, when I try the code above, I get the following message:

"Scale for 'x' is already present. Adding another scale for 'x', which
  will replace the existing scale."

The the "standard"-axis is shown.
I don't know, why the x-scale should be set already? Can anyone help please?


text:
Q: Add "dot/period" character as searchable word on mysql innodb fulltext searchs I have the exact problem as described on MySQL Match Fulltext
I need to do search with " . " (period) character, i'm using mysql 5.6.4, my table has innodb engine due i need to use some foreigns keys, the field 'fullname' has a fulltext index witg utf8_general_ci collation and it has about 34k+ records, i have in my config ini  ft_min_word_len = "2" and ft_stopword_file ="" anyway, it's work perfect with words, the problem is just the period character
so if i tried to search with %like%
WHERE  `fullname` LIKE  '%1.9%'
1,061 total, 0.0316 seg

   156 1.9 JTD Impression
    147 1.9 D
    159 1.9 JTS
    GT 1.9 JTD 16V M-Jet Impression
    159 Sportwagon 1.9 JTD
    159 1.9 JTD

With match against
WHERE MATCH (
fullname
)
AGAINST (
'1.9'
IN BOOLEAN
MODE
)
0 total, 0.0048 seg

What can i do?
Thanks

A: I've been trying to find an answer to the same question, and there doesn't seem to be a good way to handle this right now because "." is used as a deliminator. For now I'm replacing "." with "__pd" when inserting a row and when querying the table. Not ideal, but it works for me.


text:
Q: preg_match php parse html I have a problem to parse a html file using the php preg_match() function.
Here is a sample line of the html file:

15:03

The div styles show a table that I want to read out. It is like a coordinate system. To get the content I need what is inside the div tag. But to know to what content the div belongs I need the top, left and width values. The div class is not always S7. And the content (here 15:03) can be either numbers 1234 (4 digits) times (00:00) oder letters (AAA).
I am new to regular expressions so my try might look very stupid to those who are familiar to them.
Here is what I tried. But did not get any result:
    $reg_ex = "/\
(.*?)\<\/DIV\>/";
    $ret = preg_match($reg_ex,fgets($file),$outp);

Would be great if someone could help me.
Thanks a lot in advance!

A: Try
$reg_ex = "/
(.*?)<\/DIV>/";
$ret = preg_match($reg_ex,fgets($file),$outp);

[0-9] means exactly one char out of 0-9. However, you want to match one or more chars our ouf [0-9], thus, you have to use [0-9]+
Also, you only need to mask special regexp-chars (i.e., "/") and not "<", "=", and ">" by prepending with a backslash. masking " is needed because you need to have double quotes within double quotes.
In my example the class is still hardcoded to S7. If you also need to parse it use (.+) instead (which matches any char and puts it into a group).


text:
Q: "Traduzir" query do MySQL para o SQL Server 2012 Qual a query do SQL Server 2012 que corresponde à query seguinte do MySQL?
REPLACE INTO schedule SET jobname = "sqldump" , last_exec_date = NOW()

A: Para ter ação semelhante à construção REPLACE INTO (extensão SQL do MySQL) mencionada neste tópico, eis esboço do código:
-- código #1
BEGIN TRANSACTION;
DELETE from [schedule]
       where jobname = 'sqldump';
INSERT into [schedule] (jobname, last_exec_date)
       values ('sqldump', Cast(Current_timestamp as date));
COMMIT;

O código acima assume que a coluna jobname é a chave primária da tabela [schedule]. A finalização depende das respostas pendentes do autor do tópico.
Caso a coluna last_exec_date seja do tipo datetime (data e hora), deve-se retirar o Cast(), ficando somente Current_timestamp.
Para decidir com certeza como substituir o REPLACE INTO nesse caso, recomenda-se analisar qual é a ação efetiva dele no código que está migrando de MySQL para SQL Server.

A: Assumindo que jobname seja a chave da tabela schedule
IF EXISTS (SELECT * FROM [schedule ] WHERE jobname  = 'sqldump')
   UPDATE [schedule ] SET last_exec_date = GETDATE() WHERE jobname = 'sqldump'
ELSE
   INSERT INTO [schedule ] VALUES( 'sqldump', GETDATE() )

A: A função função NOW() troque por GETDATE()
No código da pergunta, a sintaxe está errada:
REPLACE INTO schedule SET jobname = "sqldump" , last_exec_date = NOW()

No MySQL a sintaxe correta deveria ser
REPLACE INTO schedule (jobname, last_exec_date) VALUES ('sqldump', NOW())

Note que REPLACE INTO é uma sintaxe do MySQL, a qual não faz parte do SQL standard.
Para entender como traduzir o comando corretamente, é preciso entender o que o REPLACE INTO faz.
O REPLACE INTO exclui o row inteiro se encontra uma chave duplicada e então faz o INSERT.
Para esse comportamente, no SQL SERVER, deve criar uma lógica onde aplica o DELETE e em seguida o INSERT. Ou seja, duas queries separadas.
Para garantir consistência, execute dentro de um TRANSACTION.
ON DUPLICATE KEY (MySQL)
Há recomendações para o uso de ON DUPLICATE KEY alternativamente ao REPLACE INTO. No entanto, a decisão é do desenvolvedor.
Esse comando não deleta o row. Quando encontra uma chave duplicada, faz um UPDATE.
Infelizmente o SQL SERVER não provê esse tipo de recurso.
Para casos onde não queira excluir e inserir é o recomendado.
No SQL Server pode combinar o comando MERGE com WHEN MATCHED.
MERGE schedule AS T
using (VALUES ('sqldump', GETDATE()))
    AS S (jobname, last_exec_date)
    ON T.jobname = 'sqldump'
WHEN MATCHED THEN
    UPDATE
    set last_exec_date = S.last_exec_date
WHEN NOT MATCHED THEN
    INSERT (jobname, last_exec_date)
    VALUES (7, S.jobname, S.last_exec_date)

Nesse exemplo usei jobname como coluna de chave primária. Não está claro na pergunta a estrutura da tabela. Então pressuponho que seja essa coluna.

Nota:
O cuidado em usar delete e insert é que no momento do insert deve inserir todas as colunas existentes. Portanto deve estar ciente do que realmente precisa.


text:
Q: User created chat rooms in Tigase In Tigase, how a connected user can "creates chat rooms" which are visible to all the contacts in roster so that any of them can "join" the room (with creator's permission)
Thanks!

A: As far as I know there is no such thing in the XMPP protocol specification, hence it is not available in the Tigase server. The simplest way to achieve something like this would be to create a chat room and put a link to the room in the presence status message. This message would be automatically visible to all contacts in the roster.
They could click on the link and join the room.
However, the main issue is whether the XMPP client you use understands XMPP links and can join room after the link is clicked.


text:
Q: Fully Connected Neural Network Nonlinearity Functions I'm a beginner in neural networks, and I'm trying to improve my fully connected neural network. I'm training on the MNIST handwritten digits set, so I have 784 input neurons (28x28 images), 10 output neurons (using one-hot encoding), and 2 hidden layers with around 30 units each.
The nonlinearity function I'm using in between the layers right now is the sigmoid function, and I'm using cross entropy loss function, and it is working. After training for a few minutes, I get about 95% accuracy on the test data.
However, I did some research, and it seems that sigmoid function is highly not recommended. By the look of things, I should use softmax activation with cross entropy loss for the output neurons, and Rectified Linear Units (ReLUs) for the hidden neurons. Is this actually the way to go though? If not, what other improvements should I make?
I will be implementing some L2 regularization later on, but for now, I just want to make sure that switching away from sigmoid will benefit me. I also know that Convolutional Neural Networks are better, but my goal right now is to optimize using a fully connected neural network.

A: sigmoid is costly to compute compared to ReLU, and has higher chance of falling into vanishing gradient problem, when propagated over layers. ReLU has the disadvantage of dying neurons, so I think better to use leaky ReLU instead, together with Batch Normalization. And, if could apply dropout, it'd decrease your chances of overfitting. Output softmax is a good choice, and I think switching from sigmoid will definitely benefit because at least you'll have faster results and have larger set of options to try out in the mean time.


text:
Q: Vue with VCalendar component: Keep data in sync with another Vue instance I'm programming a page that displays a list of meetings in a table. It's also possible to edit and delete meetings. Now I'd like to offer an alternative view using VCalendar.
Data is received from the server on page load and stored in a JS variable. Both the Vue instance containing the table and the VCalendar component share this data. If I edit a table cell, the changes are reflected in the component. But when I delete a date in the table view, it remains in the calendar.
This is the relevant HTML (edit: Added some attributes to the td):
<calendar-component></calendar-component>

            @{{ meeting.name }}

            <input type='checkbox' v-model='selected'
                   :value='meeting.id'>

    <button v-if='selected.length' @click='deleteMeetings'>
        Delete selected rows
    </button>

My JS (edit: Added handleInput method):
let table = new Vue({
    el:'#meetings-table',
    data: {
        selected:      [],
        meetings:  window.meetings,
    },
    methods: {
        /**
         * Deletes selected meetings.
         */
        deleteMeetings: function () {
            let requests = [];

            // Make a single request and store it
            for (let id of this.selected) {
                requests.push(axios.delete('/termine/' + id)
                    .then(response => {
                        // Remove meetings
                        this.meetings = this.meetings.filter(t => t.id != id);
                        // Remove id from list of selected meetings
                        this.selected = this.selected.filter(elem => elem != id);
                    }));
            }

            const axiosArray = axios.all(requests);
        },
        /**
        * Handles edits in table cells.
        */
        handleInput: function($event, meeting, field) {
            const newValue = $event.target.textContent;

            // Update value in $data
            meeting[field] = newValue;

            // AJAX request follows, but is not necessary for this example to work
        }

    }
});

The relevant parts of the component:
<template>
  <v-calendar :attributes='attributes'>

  </v-calendar>
</template>

This is what happens:

*

*I load the page containing only a single meeting. The meeting is
shown both in the table and the calendar component. Vue devtools show
it in both meetings arrays (in the component as well as in the other
Vue instance). Using the console, I can also see it in
window.meetings.

*After clicking the delete button (triggering the deleteMeetings method in my JS), the meeting is gone from the table, but remains in
the calendar, in the component's meetings array and in
window.meetings.

What do I have to change to keep the meetings arrays in sync even when deleting a meeting in the table? Note that I haven't yet implemented any methods for the calendar component.

A: Calendar, and table components should share a single state: currently selected meetings. From what I understand, right now you have that state in 2 separate places: table Vue instance, and a calendar-component, which is a child of some other Vue instance.
It may look like you're sharing the state already (with window.meetings), but it's not the case: you only initialize the same set of meetings when the components are created. And then changes in one component are not reflected in another component.
What you can try to do is to have meetings stored in the 'main' Vue app on your page, pass them as props to table and calendar components, and then trigger events from table and calendar components, when meetings array is modified. You should also define the event hanlders in the 'main' Vue app, and listen on components. A rough sketch of the solution:

    <calendar-component
        :meetings="meetings"
        @meetingUpdate="handleMeetingUpdate"
        @meetingDeleted="handleMeetingDeletion"
    ></calendar-component>

let app = new Vue({
    el:'#app',
    data: {
        meetings: []
    },
    methods: {
        handleMeetingUpdate(event) {
            //
        },
        handleMeetingDeletion(event) {
            //
        },
    }
    //
});

I hope the above is enough to point you in the right direction. If not, please let me know, and I'll do my best to help you with this further.


text:
Q: How to get id of new record which was ignored(replaced) becase of unique fields I need to know the ID of newly created record, but this record has unique field:
CREATE TABLE materials (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name TEXT,
    color_id INTEGER,
    count INTEGER);

CREATE TABLE colors (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name TEXT UNIQUE ON CONFLICT IGNORE);

I'm using simple TextBox, to set color, I want it to be inserted and then receive it's id. How can I do this?

A: For example:
INSERT INTO color(name)
VALUES("blue one")
SELECT SCOPE_IDENTITY()
You can keep result in variable and then use in another query. You can also use some ORM and it will handle for you.
Possible duplication of that one.


text:
Q: Android: Intent's extra is missing (working with widget) I want to make a widget with 2 Buttons(one is a Textview with a number). One button should increment the number and the other decrement it.
Here are my variables(2x action-names and an int for the number)
    private static final String PLUS_ONE = "Plus1";
    private static final String MINUS_ONE = "minus1";
    static int counter = 0;

The onUpdate():
 @Override
 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
 final int N = appWidgetIds.length;
 for (int i=0; i<N; i++) {
     int appWidgetId = appWidgetIds[i];
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
     remoteViews.setOnClickPendingIntent(R.id.counter_widget, getPendingSelfIntent(context, PLUS_ONE, counter));
     remoteViews.setOnClickPendingIntent(R.id.img_downWid, getPendingSelfIntent(context, MINUS_ONE, counter));

     appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
 }}

getPendingSelfIntent is my method to create an intent, putting an int value in it and returning an PendingIntent
Here in detail:
    protected PendingIntent getPendingSelfIntent(Context context, String action, int i) {
    Intent intent = new Intent(context, Plus1CounterAppWidgetProvider.class);
    intent.setAction(action);
    intent.putExtra("safeInt", i);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);}

and eventually my onReturn() in which I want to set the counter to the value I gave to the Intent and perform the action:
 @Override
 public void onReceive(Context context, Intent intent) {
 super.onReceive(context, intent);
 counter = intent.getIntExtra("safeInt", 0);

 if (PLUS_ONE.equals(intent.getAction())) {
     counter++;
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
     remoteViews.setTextViewText(R.id.counter_widget, Integer.toString(counter));
     AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, Plus1CounterAppWidgetProvider.class), remoteViews);
 }

 if (MINUS_ONE.equals(intent.getAction())) {
     counter--;
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
     remoteViews.setTextViewText(R.id.counter_widget, Integer.toString(counter));
     AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, Plus1CounterAppWidgetProvider.class), remoteViews);
 }}

By calling
counter = intent.getIntExtra("safeInt", 0);

the counter is always set to 0, which means that there is no extra value.
I just do not get why! Any Solutions? :)

A: I found an other solution.
I just used SharedPreferences instead of the Intent and it worked! :)
Here is the code:
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;

public class Plus1CounterAppWidgetProvider extends AppWidgetProvider{

private static final String PLUS_ONE = "Plus1";
private static final String MINUS_ONE = "Minus1";
private static final String REFRESH_COUNTER = "Refresh";
static int counter = 0;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[]  appWidgetIds) {
 final int N = appWidgetIds.length;
 for (int i=0; i<N; i++) {
     int appWidgetId = appWidgetIds[i];
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(),  R.layout.plus1counter_widget);
     remoteViews.setOnClickPendingIntent(R.id.counter_widget, getPendingSelfIntent(context, PLUS_ONE));
     remoteViews.setOnClickPendingIntent(R.id.img_downWid, getPendingSelfIntent(context, MINUS_ONE));
     remoteViews.setOnClickPendingIntent(R.id.img_refreshWid, getPendingSelfIntent(context, REFRESH_COUNTER));
     appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
  }
 }

 @Override
 public void onReceive(Context context, Intent intent) {
 super.onReceive(context, intent);

 SharedPreferences sharedPref = context.getSharedPreferences("com.plus1counter.safeFile", Context.MODE_PRIVATE);
 counter = sharedPref.getInt("safeFile", 0);
 if(counter == 100){
     counter = 0;
 }

 if (PLUS_ONE.equals(intent.getAction())) {
     counter++;
     writeSharedPrefs(sharedPref);
 }

 if (MINUS_ONE.equals(intent.getAction())) {
     counter--;
     writeSharedPrefs(sharedPref);
 }

 if(REFRESH_COUNTER.equals(intent.getAction())){
     counter = 0;
     writeSharedPrefs(sharedPref);
 }
 RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.plus1counter_widget);
 remoteViews.setTextViewText(R.id.counter_widget, Integer.toString(counter));
 AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, Plus1CounterAppWidgetProvider.class), remoteViews);
 }

 public void writeSharedPrefs(SharedPreferences sharedPref){
 SharedPreferences.Editor editor = sharedPref.edit();
 editor.putInt("safeFile", counter);
 editor.commit();
 }

 protected PendingIntent getPendingSelfIntent(Context context, String action) {
 Intent intent = new Intent(context, Plus1CounterAppWidgetProvider.class);
 intent.setAction(action);
 return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 }

 }